交叉点数量列表

时间:2018-04-01 05:35:46

标签: python list

我有2个列表

[2, 1]

结果,我需要每对内部列表中相等位置的相等元素的数量。对于上面的示例,预期结果将是def intersect (l1,l2,count): count=0 for i in l1: if i in(l2): count=count+1.0 return count c=[[1,2], [2,3]] b=[[1,2], [2,0]] count1=[] count=0 for i in c: for j in b: count1.append(intersect(i,j,0))

我目前有:

post()

2 个答案:

答案 0 :(得分:2)

它们的行数是否相等?在这种情况下,我们可以使用numpy:

import numpy as np

c = [[1,2], [2,3]]
b = [[1,2], [2,0]]
output = (np.array(c) == np.array(b)).sum(axis=1).tolist()

[2,1]

如果我们有不同的长度,我们可以拉链并使用它:

output = [(np.array(i[0]) == np.array(i[1])).sum() for i in list(zip(c,b))]

答案 1 :(得分:0)

此解决方案只是压缩您的列表,这将导致忽略内部或外部列表中的任何多余元素,因为示例数据应该清楚

def intersection(b, c):
    count = []
    for l1, l2 in zip(b, c):
        n_same = sum([1 for x1, x2 in zip(l1, l2) if x1 == x2])
        count.append(n_same)        
    return count

# or as a one-liner
intersection = lambda b, c: [sum([1 for x1, x2 in zip(l1, l2) if x1 == x2]) for l1, l2 in zip(b, c)]

#     x  x    x                          x     x       x   <-- intersection found
c = [[1, 2], [2, 3], [3, 0], [6, 7, 8], [8, 7, 8], [1, 2, 3, 4]]
b = [[1, 2], [2, 0], [1, 2], [7, 6, 6], [8, 8, 8], [2, 2], [3, 4]]

print intersection(b, c)

>>> [2, 1, 0, 0, 2, 1]