繁体   English   中英

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

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

我找到了一些解决方案,但没有一个是我需要的。

例如:

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"

结果:狗,go,长

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

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

如果集合中的每个项目都是True ,则all返回True 当不是每个项目都为True时,它也将返回False

例如:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM