如何检查 iterable_2 中是否有 Iterable_1

How to check if Iterable_1 in iterable_2

如何在不迭代 list_1 的情况下检查 list_1 list_2 中?有没有具体的'pythonic'方法或者最好坚持:

for i in list_1:
  if i in list_2:

谢谢!

您似乎对 list_1 中的每个元素也都在 list_2 中的情况感兴趣。在那种情况下,一个简单的

set(list_1) <= set(list_2)

有效。

当然——如果 list_2 是一个列表列表,而您想知道 list_1 是否是这些列表之一,那么简单

list_1 in list_2

有效。

或者,您可能会问 list_1 是否是 list_2 的 切片 。只需检查

list_1 in (list_2[i:j] for j in range(len(list_2)+1) for i in range(j))

您还可以检查 list_1 是否是 list_2 的子多重集,或者 list_1 是否是 list_2 的递增子序列。我会把这些留作练习。

Python 对地图和过滤器有一些功能支持,有助于避免迭代级别。

对于内部迭代conditions/early returns,any和all函数有效。

此外,集合运算(相交、并集、差集)也很有用。这可能是我在查看列表 1 中的元素是否在列表 2 中时会选择的。

list_1 = [ 2, 3 ]
list_2 = [ 1, 2, 3, 4 ]

print set(list_1) in set(list_2) # True

# a more functional approach, although really only makes sense for more specific complex examples!
import operator,itertools,functools
is_in_list_2 = functools.partial(operator.contains,list_2)
print all(itertools.imap(is_in_list_2,list_1)) # will hopefully not call contains more than it needs to!