我试图匹配两个由元组(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值将是整数,不会重复。

最佳答案

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)]

关于python - 在Python中将两个列表拟合和对齐,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39117304/

10-12 18:40