[英]Pythonic way of checking if several elements are in a list
I have this piece of code in Python: 我在Python中有这段代码:
if 'a' in my_list and 'b' in my_list and 'c' in my_list:
# do something
print my_list
Is there a more pythonic way of doing this? 有更多的pythonic方式吗?
Something like (invalid python code follows): 像(无效的python代码如下):
if ('a', 'b', 'c') individual_in my_list:
# do something
print my_list
if set("abc").issubset(my_list):
# whatever
The simplest form: 最简单的形式:
if all(x in mylist for x in 'abc'):
pass
Often when you have a lot of items in those lists it is better to use a data structure that can look up items without having to compare each of them, like a set
. 通常,当您在这些列表中有很多项目时,最好使用可以查找项目的数据结构,而无需比较每个项目,例如
set
。
You can use set operators: 您可以使用set运算符:
if set('abc') <= set(my_list):
print('matches')
superset = ('a', 'b', 'c', 'd')
subset = ('a', 'b')
desired = set(('a', 'b', 'c'))
assert desired <= set(superset) # True
assert desired.issubset(superset) # True
assert desired <= set(subset) # False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.