检查list1中的所有元素是否都存在于list2中python

Check if all elements in list1 exist in list2 python

我希望能够找到 list1 中的所有元素是否都存在于 list2 中,这两个列表都包含字符。相同元素在每个列表中出现的次数很重要。

我尝试使用子集,但是它没有记录项目在列表中出现的次数

例如

list1 = [a, b, c]
list2 = [a, b, c, b]

它会发现 list2 是 list1 的子集,而我只希望我的函数在以下情况下执行:

list1 = [a, b, c, b, i]
list2 = [a, c, b, b]

因为这意味着列表 2 中的 所有 项出现在列表 1 中。

如果有人感兴趣,使用计数器对于大字符串来说效率低下,所以我最终将 list1 的所有元素添加到字典中,值是每个元素出现的次数并减去 list2 的所有元素。如果任何值最终为负,则 list2 中的所有项目都不会出现在 list1

您可以使用 issuperset:

>>> list1 = ['a', 'b', 'c', 'b', 'i']
>>> list2 = ['a', 'c', 'b', 'b']
>>> set(list1).issuperset(set(list2)) # all items of list2 exist in list1
True
>>> set(list2).issuperset(set(list1)) # all items of list1 does not exist in list 2
False

您可以使用collections.Counter

from collections import Counter
list1 = ['a', 'b', 'c']
list2 = ['a', 'b', 'c', 'b']    
c1 = Counter(list1)
c2 = Counter(list2)

for key, count in c1.iteritems():
    if c2[key] < count:
        break
else:
    print 'list2 has all the chracters in list1'

您可以使用 collections.Counter 对两个列表中的项目进行计数,并检查第一个列表中相应项目的计数是否大于第二个列表中相应项目的计数:

>>> from collections import Counter
>>> c = Counter("abcbi")
>>> d = Counter("acbb")
>>> c.subtract(d)
>>> if all(v >= 0 for k, v in c.items()):
...     print("All items exist")
... 
All items exist

对于您的问题,您需要

  1. 验证 list2 中的所有元素都出现在 list1 中,但
  2. list2 中没有元素比 list2
  3. 中出现得更多

使用 collections.Counter:

可以很容易地做到这一点
import collections

def f(list1, list2):
    d1 = collections.Counter(list1)
    d2 = collections.Counter(list2)
    return set(d1.keys()).issuperset(set(d2.keys())) \
       and all(d2[k] <= d1[k] for k in d1.keys())

这首先检查(使用 set.issupersetlist2 的所有不同元素是否包含在 list1 中。如果这是真的,它会检查每个元素在 list2 中出现的频率,并验证它在 list1.

中出现的频率较低(或相等)