Home > Mobile >  How to check if list2 has all the contents of one of list1's nested lists?
How to check if list2 has all the contents of one of list1's nested lists?

Time:10-10

`list1 = [[1, 2, 3], [4, 5, 6]]
 list2 = [1 ,8 ,7 ,2, 0, 3]`

Output should say, that list2 contains all integers in one of list1's sublists.

CodePudding user response:

If there are no duplicates in either list:

s2 = set(list2)
result = any(all(e in s2 for e in sub) for sub in list1)

If there might be duplicates and you need all occurrences to appear in list2, you can use collections.Counter:

from collections import Counter

c2 = Counter(list2)
result = any(not (Counter(sub) - c2) for sub in list1)

CodePudding user response:

A version that will take duplicates into account:

from collections import Counter

list_1 = [[1, 2, 3], [4, 5, 6]]
list_2 = [1, 8, 7, 2, 0, 3]

counts = Counter(list_2)
res = any(len(Counter(e) - counts) == 0 for e in list_1)
print(res)

Output

True
  • Related