If I have two lists that look like this:
list1 = ['a', 'a', 'b', 'c']
list2 = ['a', 'a', 'a', 'b']
How can I check if the second list is contained in the first? I assume sets would not work, because the letters can be repeated.
If I have two lists that look like this:
list1 = ['a', 'a', 'b', 'c']
list2 = ['a', 'a', 'a', 'b']
How can I check if the second list is contained in the first? I assume sets would not work, because the letters can be repeated.
Sets won't work if the frequency matter but counting the frequency will:
from collections import Counter
list1 = ['a', 'a', 'b', 'c']
list2 = ['a', 'a', 'a', 'b']
cn1, cn2 = Counter(list1), Counter(list2)
print(all(cn2[k] <= v for k, v in cn1.items()))
If the count of each string in list2 is <= to the amount of times it appears in list1 you have all the strings from list2 in list1, which for the lists in your question would return False but for,
list1 = ['a', 'a', 'b', 'c', 'a']
list2 = ['a', 'a', 'a', 'b']
would return True
as you have the same amount of a's and a b.
Similar to @Padraic_Cunningham's answer:
from collections import Counter
def contained(l1, l2):
cntr1 = Counter(list1)
cntr2 = Counter(list2)
for k in cntr2:
if cntr2[k] != cntr1.get(k):
return False
return True
list1 = ['a', 'a', 'b', 'c']
list2 = ['a', 'a', 'a', 'b']
contained(list1, list2)