从两个列表中查找共同的元素 [英] Finding common elements from two lists of lists
问题描述
我有两个包含一些3D坐标的列表列表(例如):
I have two lists of lists containing some 3D coordinates like this (for example):
a = [[1, 2, 3], [4, 5, 6], [4, 2, 3]]
b[0] = [[11, 22, 3], [12, 34, 6], [41, 2, 34], [198, 213, 536], [1198, 1123, 1156]]
b[1] = [[11, 22, 3], [42, 25, 64], [43, 45, 23]]
b[2] = [[3, 532, 23], [4, 5, 6], [98, 23, 56], [918, 231, 526]]
b[n] = [[11, 22, 3], [42, 54, 36], [41, 2432, 34]]
查找"b"的任何元素在列表"a"中是否具有任何坐标的快速方法是什么?例如,在给定的示例中,"a [2]"和"b [2] [1]"相同,因此我希望程序返回"true".
What will be a fast way of finding if any of the elements of "b" have any coordinate in the list "a"? For example, in the given example "a[2]" and "b[2][1]" are the same and so I want the program to return "true".
推荐答案
将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)])
这篇关于从两个列表中查找共同的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!