Python 如何检查以下所有项目是否都在列表中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3931541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if all of the following items are in a list?
提问by sirex
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?
但是,查找列表中是否存在所有项目的最佳 Pythonic 方法是什么?
Searching through the docs I found this solution:
搜索文档我找到了这个解决方案:
>>> l = ['a', 'b', 'c']
>>> set(['a', 'b']) <= set(l)
True
>>> set(['a', 'x']) <= set(l)
False
Other solution would be this:
其他解决方案是这样的:
>>> 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.
但在这里你必须多打字。
Is there any other solutions?
还有其他解决方案吗?
采纳答案by Glenn Maynard
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.
像<=Python 中的运算符通常不会被覆盖以表示与“小于或等于”显着不同的东西。标准库这样做是不寻常的——对我来说,它闻起来像是遗留 API。
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.issubset. 请注意,您不需要将参数转换为集合;如果需要,它会为您做到这一点。
set(['a', 'b']).issubset(['a', 'b', 'c'])
回答by tsimbalar
I would probably use setin the following manner :
我可能会set以下列方式使用:
set(l).issuperset(set(['a','b']))
or the other way round :
或者反过来:
set(['a','b']).issubset(set(l))
I find it a bit more readable, but it may be over-kill. Sets are particularly useful to compute union/intersection/differences between collections, but it may not be the best option in this situation ...
我发现它更具可读性,但它可能会过度杀伤。集合对于计算集合之间的并集/交集/差异特别有用,但在这种情况下它可能不是最佳选择......
回答by martineau
I like these two because they seem the most logical, the latter being shorter and probably fastest (shown here using setliteral syntax which has been backportedto Python 2.7):
我喜欢这两个,因为它们看起来最合乎逻辑,后者更短并且可能最快(此处使用set已向后移植到 Python 2.7 的文字语法 显示):
all(x in {'a', 'b', 'c'} for x in ['a', 'b'])
# or
{'a', 'b'}.issubset({'a', 'b', 'c'})
回答by Max
What if your lists contain duplicates like this:
如果您的列表包含这样的重复项怎么办:
v1 = ['s', 'h', 'e', 'e', 'p']
v2 = ['s', 's', 'h']
Sets do not contain duplicates. So, the following line returns True.
集合不包含重复项。因此,以下行返回 True。
set(v2).issubset(v1)
To count for duplicates, you can use the code:
要计算重复项,您可以使用以下代码:
v1 = sorted(v1)
v2 = sorted(v2)
def is_subseq(v2, v1):
"""Check whether v2 is a subsequence of v1."""
it = iter(v1)
return all(c in it for c in v2)
So, the following line returns False.
因此,以下行返回 False。
is_subseq(v2, v1)
回答by Emirhan ?zlen
This was what I was searching online but unfortunately found not online but while experimenting on python interpreter.
这是我在网上搜索的内容,但不幸的是在网上找到的,但在 python 解释器上进行了试验。
>>> case = "caseCamel"
>>> label = "Case Camel"
>>> list = ["apple", "banana"]
>>>
>>> (case or label) in list
False
>>> list = ["apple", "caseCamel"]
>>> (case or label) in list
True
>>> (case and label) in list
False
>>> list = ["case", "caseCamel", "Case Camel"]
>>> (case and label) in list
True
>>>
and if you have a looong list of variables held in a sublist variable
如果你有一个很长的变量列表 sublist variable
>>>
>>> list = ["case", "caseCamel", "Case Camel"]
>>> label = "Case Camel"
>>> case = "caseCamel"
>>>
>>> sublist = ["unique banana", "very unique banana"]
>>>
>>> # example for if any (at least one) item contained in superset (or statement)
...
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
False
>>>
>>> sublist[0] = label
>>>
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
True
>>>
>>> # example for whether a subset (all items) contained in superset (and statement)
...
>>> # a bit of demorgan's law
...
>>> next((False for item in sublist if item not in list), True)
False
>>>
>>> sublist[1] = case
>>>
>>> next((False for item in sublist if item not in list), True)
True
>>>
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
True
>>>
>>>
回答by Jundullah
An example of how to do this using a lambda expression would be:
如何使用 lambda 表达式执行此操作的示例如下:
issublist = lambda x, y: 0 in [_ in x for _ in y]
回答by Julio Cezar Silva
Not OP's case, but - for anyone who wants to assert intersection in dictsand ended up here due to poor googling (e.g. me) - you need to work with dict.items:
不是 OP 的情况,但是 - 对于任何想要在dicts 中断言交集 并由于谷歌搜索不佳(例如我)而在这里结束的人 - 您需要使用dict.items:
>>> a = {'key': 'value'}
>>> b = {'key': 'value', 'extra_key': 'extra_value'}
>>> all(item in a.items() for item in b.items())
True
>>> all(item in b.items() for item in a.items())
False
That's because dict.itemsreturns tuples of key/value pairs, and much like any object in Python, they're interchangeably comparable
这是因为dict.items返回键/值对的元组,就像 Python 中的任何对象一样,它们可以互换比较

