如何轻松检查 Python 一个列表中的所有项目都包含在另一个列表中?

How can I easily check in Python that all items in one list are included in the other list?

我找到了一些解决方案,但其中 none 是我需要的。

例如:

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

Counter(list1) == Counter(list2) -> True,但我需要 False 因为双 'a' //// set(list1) == set(list2) -> True, 但我还需要 False.

我想写一个小代码来从列表中搜索可能的单词。

示例:

wordCollection = ["dog", "go", "home", "long"] //// 输入字符:“NLGUCOBAD”

结果:狗,走,长

您可以将 all 与一个简单的表达式结合使用:

result = all((list1.count(x) == list2.count(x)) for x in list1)

all returns True 如果集合中的每一项都是 True。当不是每个项目都是 True.

时,它会选择 return False

例如:

all([True, True, True, True, True])
>>> True

all([True, False, True, True, True])
>>> False

考虑到这一点,您可以检查 list1 中每个元素的计数是否与 list2 中的相同。这就是 list1.count(x) == list2.count(x) 的来源。