[英]Python: Check if element is not in two lists?
我需要检查一个元素是否不在两个列表中。 我目前有:
if ele not in lista:
if ele not in listb:
do stuff
使用以下代码不起作用。 有没有更有效的方法来完成上面的python?
if ele not in lista and listb:
do stuff
if ele not in lista and ele not in listb:
# do stuff
要么
if ele not in lista + listb:
# do stuff
但第二个选项将涉及列表连接,这可能会导致大型列表的内存问题,它也必须两次通过列表。 要解决这个问题,你可以使用itertools
:
from itertools import chain
if ele not in chain(lista, listb):
# do stuff
如果你要不断检查会员,你要使用一set
具有O(1)
的(摊销)查找,而不是O(n)
的列表。
例如。
items_set = set(chain(lista, listb))
if ele in items_set: # this membership check will be a lot faster
# do stuff
if ele not in lista and ele not in listb:
迟到但我只是想添加一些更酷的东西
假设两个列表长度相等
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = all("h" not in pair for pair in zip(a,b))
如果它们长度不等:
from itertools import zip_longest
a = [1,2,3,4,5]
b = [6,7,8,9,10,11,12,13]
c = all("h" not in pair for pair in zip_longest(a,b))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.