将最里面的列表转换b
成一个集合(s
),然后迭代a
检查是否a
存在任何项目s
。
tot_items_b = sum(1 for x in b for y in x) #total items in b
集合提供O(1)
查找,因此整体复杂性将是:
O(max(len(a), tot_items_b))
def func(a, b):
#sets can't contain mutable items, so convert lists to tuple while storing
s = set(tuple(y) for x in b for y in x)
#s is set([(41, 2, 34), (98, 23, 56), (42, 25, 64),...])
return any(tuple(item) in s for item in a)
演示:
>>> a = [[1, 2, 3], [4, 5, 6], [4, 2, 3]]
>>> b = [[[11, 22, 3], [12, 34, 6], [41, 2, 34], [198, 213, 536], [1198, 1123, 1156]], [[11, 22, 3], [42, 25, 64], [43, 45, 23]], [[3, 532, 23], [4, 5, 6], [98, 23, 56], [918, 231, 526]]]
>>> func(a,b)
True
帮助any
:
>>> print any.__doc__
any(iterable) -> bool
Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.
使用集合交集获取所有公共元素:
>>> s_b = set(tuple(y) for x in b for y in x)
>>> s_a = set(tuple(x) for x in a)
>>> s_a & s_b
set([(4, 5, 6)])