如何检查以下所有项目是否都在列表中? [英] How to check if all of the following items are in a list?
问题描述
我发现,存在一个相关的问题,即如何查找列表中是否至少存在一项:
如何检查以下内容之一项目在列表中?
I found, that there is related question, about how to find if at least one item exists in a list:
How to check if one of the following items is in a list?
但是,查找列表中是否存在所有项的最佳方式是什么?
But what is the best and pythonic way to find whether all items exists in a list?
搜索文档后,我发现了此解决方案:
Searching through the docs I found this solution:
>>> 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
但是在这里您必须进行更多的键入.
But here you must do more typing.
还有其他解决方案吗?
推荐答案
Python中的<=
之类的运算符通常不会被覆盖以表示与小于或等于"有显着不同的东西.对于标准库来说,这样做是不寻常的-对我来说,它闻起来就像旧版API.
Operators like <=
in Python are generally not overriden to mean something significantly different than "less than or equal to". It's unusual for the standard library does this--it smells like legacy API to me.
使用等效的且更明确命名的方法set.issubset
.注意,您不需要将参数转换为集合;会在需要时为您完成.
Use the equivalent and more clearly-named method, set.issubset
. Note that you don't need to convert the argument to a set; it'll do that for you if needed.
set(['a', 'b']).issubset(['a', 'b', 'c'])
这篇关于如何检查以下所有项目是否都在列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!