两个列表列表之间的公共元素(嵌套列表的交集)

时间:2015-06-18 09:18:59

标签: python python-2.7 numpy nested-lists

我在2D中有两个大的点列表,我想找到它们的共同子列表,如果它们有一些。这两个列表都很大,效率也是个问题。

t1 = [[3, 41], [5, 82], [10, 31], [11, 34], [14, 54]]
t2 = [[161, 160], [169, 260], [187, 540], [192, 10], [205, 23]]

我尝试过如下所示的itertools,但是我得到了" ValueError:具有多个元素的数组的真值是不明确的。使用a.any()或a.all()"。

for i in itertools.chain.from_iterable(t1):
    if i in t2:
        print "yes",i

I tried the first answer from here too,但我得到' numpy.int64'对象不可迭代。 此外,我认为这个简单的代码可行,但需要花费很多时间:

intersection = [i for i in t1 if i in t2]

有什么建议吗?感谢。

2 个答案:

答案 0 :(得分:5)

列表不可清除所以我们需要将内部列表转换为元组然后我们可以使用set intersection来查找公共元素

t1 = [[3, 41], [5, 82], [10, 31], [11, 34], [14, 54]]
t2 = [[161, 160], [169, 260], [187, 540], [192, 10], [205, 23], [3,41]]

nt1 = map(tuple, t1)
nt2 = map(tuple, t2)

st1 = set(nt1)
st2 = set(nt2)

print st1.intersection(st2)

<强>输出

set([3,41])

由于我们将列表设置为集合,因此我们不考虑重复。考虑以下输入

  t1 = [[3, 41], [3, 41], [5, 82], [10, 31], [11, 34], [14, 54]]
  t2 = [[3,41], [3,41], [161, 160], [169, 260], [187, 540], [192, 10], [205, 23]]

我们在两个列表中都有两个[3,41]但是前面的python程序在输出中只输出一个[3,41]。以下程序将通过最初计数并在之后重复它们来处理重复的条目。

t1 = [[3, 41], [3, 41], [5, 82], [10, 31], [11, 34], [14, 54]]
t2 = [[3,41], [3,41], [161, 160], [169, 260], [187, 540], [192, 10], [205, 23]]

nt1 = map(tuple, t1)
nt2 = map(tuple, t2)

st1 = set(nt1)
st2 = set(nt2)

from collections import defaultdict
d1 = defaultdict(int)
d2 = defaultdict(int)
for i in nt1:
    d1[i] += 1#counting element occurrence from first list

for i in nt2:
    d2[i] += 1 #counting element occurrence from second list

result_list = []

for i in st1.intersection(st2):
    min_count = min(d1[i], d2[i]) #selecting the minimum one to multiply
    result_list+=map(lambda x:list(i), xrange(0, min_count))

print result_list

<强>输出

[[3, 41], [3, 41]]

答案 1 :(得分:1)

如果您真的只使用list,那么您可以从列表中创建set并根据您的情况使用set().intersection() -

l1 = [[1,2],[2,3]]
l2 = [[3,4],[2,3]]
list(set(map(tuple,l1)).intersection(set(map(tuple,l2))))
>> [(2, 3)]

但非常非常大lists这个方法可能很慢。

编辑:使用map功能。