且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从两个列表中查找共同的元素

更新时间:2022-11-13 14:44:32

b的最里面的列表转换为set(s),然后遍历a以检查a中是否有任何项目是否存在于s中.

Convert the innermost lists of b into a set(s), and then iterate over a to check whether any item in a exist in s or not.

tot_items_b = sum(1 for x in b for y in x) #total items in b

集合提供了O(1)查找,因此总体复杂度将为:

Sets provide an O(1) lookup, so the overall complexity is going to be :

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.

使用集合交集获取所有公共元素:

Use set intersection to get all the common elements:

>>> 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)])