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

kal*_*yan 1 python numpy nested-lists python-2.7

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

t1 = [[3, 41], [5, 82], [10, 31], [11, 34], [14, 54]]
t2 = [[161, 160], [169, 260], [187, 540], [192, 10], [205, 23]]
Run Code Online (Sandbox Code Playgroud)

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

for i in itertools.chain.from_iterable(t1):
    if i in t2:
        print "yes",i
Run Code Online (Sandbox Code Playgroud)

我也从这里尝试了第一个答案,但我得到'numpy.int64'对象不可迭代. 另外,我认为这个简单的代码可行,但需要花费很多时间:

intersection = [i for i in t1 if i in t2]
Run Code Online (Sandbox Code Playgroud)

有什么建议?谢谢.

k4v*_*vin 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)
Run Code Online (Sandbox Code Playgroud)

产量

set([3,41])
Run Code Online (Sandbox Code Playgroud)

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

  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]]
Run Code Online (Sandbox Code Playgroud)

我们在两个列表中都有两个[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
Run Code Online (Sandbox Code Playgroud)

产量

[[3, 41], [3, 41]]
Run Code Online (Sandbox Code Playgroud)