How to check if all elements of 1 list are in the *same quantity* and in any order, in the list2?
Use collections.Counter
to convert to a dict_items
view Set of (value, count) pairs. Then you can use normal set operations.
from collections import Counter
def a_all_in_b(a, b):
"""True only if all elements of `a` are in `b` in the *same quantity* (in any order)."""
return Counter(a).items() <= Counter(b).items()
Note that Counter
works on hashable elements only, because it's a subclass of dict
.
Modify this answer to Checking if list is a sublist to check for equality of occurences:
from collections import Counter
list1 = [2,2,2,6]
list2 =[2,6,2,5,2,4]
def same_amount(a,b):
c1 = Counter(a)
c2 = Counter(b)
for key,value in c1.items():
if c2[key] != value:
return False
return True
print(same_amount(list1,list2))
print(same_amount(list1 + [2],list2))
Output:
True
False
There is almost no transfere-knowledge needed to create this answer, thats why I suggested it as dupe. This question is simply a more specific case of what Checking if list is a sublist discussed.