在Python中将两个列表组合在一起并对齐

时间:2016-08-24 07:45:00

标签: python python-3.x

我试图匹配由元组(x,y,z)组成的两个列表。我需要根据z值将它们组合在一起,并删除任何包含两个列表不常见的z值的元组。

输入:

a = [(0,0,0),(3,4,1),(5,3,2),(1,2,3)]
b = [(0,1,1),(2,3,2),(3,4,4)]

输出:

a1 = [(3,4,1),(5,3,2)]
b1 = [(0,1,1),(2,3,2)]

z值将是整数,不会重复。

4 个答案:

答案 0 :(得分:4)

common_z = set([tup[2] for tup in a]).intersection([tup[2] for tup in b])
a_ = [tup for tup in a if tup[2] in common_z]
b_ = [tup for tup in b if tup[2] in common_z]

>>> a_
[(3, 4, 1), (5, 3, 2)]

>>> b_
[(0, 1, 1), (2, 3, 2)]

答案 1 :(得分:0)

这将部分满足您的要求,是一个很好的起点。 从这里你可以调整它以返回重复的情况以及如何订购你的东西。

a= [(0,0,0),(3,4,1),(5,3,2),(1,2,3)]
b= [(0,1,1),(2,3,2),(3,4,4)]
a1=[] 
b1=[]
for i in a:
    for j in b:
        if i[2] == j[2]:
            a1.append(i)
            b1.append(j)

答案 2 :(得分:0)

您可以使用set作为:

来实现它
>>> a = [(0,0,0),(3,4,1),(5,3,2),(1,2,3)]
>>> b = [(0,1,1),(2,3,2),(3,4,4)]
# Intersection of z co-ordinates in 'a' and 'b' list
>>> z_ab = set(map(lambda x: x[2], a)) & set(map(lambda x: x[2], b))  

>>> new_a = filter(lambda x: x[2] in z_ab, a)
# new_a = [(3, 4, 1), (5, 3, 2)]
>>> new_b = filter(lambda x: x[2] in z_ab, b)
# new_b = [(0, 1, 1), (2, 3, 2)]

答案 3 :(得分:0)

您可以将代码更改为:

a = [(0,0,0),(3,4,1),(5,3,2),(1,2,3)]
b = [(0,1,1),(2,3,2),(3,4,4)]

a_dict = {z:[x,y] for x,y,z in a}
b_dict = {z:[x,y] for x,y,z in b}

a1=[]
b1=[]

for item in a_dict.keys():
    if item in b_dict.keys():
        a_dict[item].append(item)
        a1.append(tuple(a_dict[item]))
        b_dict[item].append(item)
        b1.append(tuple(b_dict[item]))

print(a1)
print(b1)