【发布时间】:2011-04-25 07:07:47
【问题描述】:
我发现有一个相关的问题,关于如何查找列表中是否存在至少一项:
How to check if one of the following items is in a list?
但是,找出所有项目是否都存在于列表中的最好的 Pythonic 方法是什么?
通过文档搜索我找到了这个解决方案:
>>> l = ['a', 'b', 'c']
>>> set(['a', 'b']) <= set(l)
True
>>> set(['a', 'x']) <= set(l)
False
其他解决方案是这样的:
>>> l = ['a', 'b', 'c']
>>> all(x in l for x in ['a', 'b'])
True
>>> all(x in l for x in ['a', 'x'])
False
但是在这里你必须做更多的输入。
还有其他解决办法吗?
【问题讨论】:
-
set(smaller) <= set(larger)有什么问题? -
我认为您使用“所有”的第二个解决方案对我来说看起来很好而且是 Python 的。
-
与Python: See if one set contains another entirely? - Stack Overflow 相同的问题,除了列表/集合的区别。