How to check if all items in a list are there in another list?

前端 未结 6 1083
误落风尘
误落风尘 2020-11-27 20:08

I have two lists say

List1 = [\'a\',\'c\',\'c\']
List2 = [\'x\',\'b\',\'a\',\'x\',\'c\',\'y\',\'c\']

Now I want to find out if all element

6条回答
  •  执笔经年
    2020-11-27 20:48

    When number of occurrences doesn't matter, you can still use the subset functionality, by creating a set on the fly:

    >>> list1 = ['a', 'c', 'c']
    >>> list2 = ['x', 'b', 'a', 'x', 'c', 'y', 'c']
    >>> set(list1).issubset(list2)
    True
    

    If you need to check if each element shows up at least as many times in the second list as in the first list, you can make use of the Counter type and define your own subset relation:

    >>> from collections import Counter
    >>> def counterSubset(list1, list2):
            c1, c2 = Counter(list1), Counter(list2)
            for k, n in c1.items():
                if n > c2[k]:
                    return False
            return True
       
    >>> counterSubset(list1, list2)
    True
    >>> counterSubset(list1 + ['a'], list2)
    False
    >>> counterSubset(list1 + ['z'], list2)
    False
    

    If you already have counters (which might be a useful alternative to store your data anyway), you can also just write this as a single line:

    >>> all(n <= c2[k] for k, n in c1.items())
    True
    

提交回复
热议问题