以共同的值加入两组元组

时间:2018-05-10 05:44:08

标签: python set set-union

假设:

setA = [(1, 25), (2, 24), (3, 23), (4, 22), (5, 21), (6, 20), 
         (7, 19), (8, 18), (9, 17), (10, 16), (11, 15), (12, 14), 
         (13, 13),(14, 12), (15, 11), (16, 10), (17, 9), (18, 8), 
         (19, 7),(20, 6), (21, 5), (22, 4), (23, 3), (24, 2), (25, 1)]

setB = [(1, 19), (2, 18), (3, 17), (4, 16), (5, 15), (6, 14), (7, 13),
         (8, 12), (9, 11), (10, 10), (11, 9), (12, 8), (13, 7), (14, 6),
         (15, 5), (16, 4), (17, 3), (18, 2), (19, 1)]

如何将每组中每个元组的第一个元素组合为两个集合作为公共键值。因此,对于每组中位置1的元组,它将分别为(1,25)和(1,19)。加在一起会产生:(25,1,19)

(25,1,19)
(24,2,18)
(23,3,17)
...
(7,19,1)
(6,20,none)
...
(2,24,none)
(1,25,none)

注意:必须保持输出元组的顺序。示例:

(setA value, common value, setB value)
(setA value, common value, setB value)etc...

注意:必须使用Python 2.7x标准库

我尝试做[(a,b,c) for (a,b),(b,c) in zip(setA,setB)]之类的事情,但我并不完全理解正确的语法和逻辑。

谢谢。

2 个答案:

答案 0 :(得分:5)

似乎你想要的东西可以像列表理解中的setB上的字典查找那样轻松实现。

mapping = dict(setB)
out = [(b, a, mapping.get(a)) for a, b in setA]

print(out)
[(25, 1, 19),
 (24, 2, 18),
 (23, 3, 17),
 (22, 4, 16),
 (21, 5, 15),
 (20, 6, 14),
 (19, 7, 13),
 (18, 8, 12),
 (17, 9, 11),
 (16, 10, 10),
 (15, 11, 9),
 (14, 12, 8),
 (13, 13, 7),
 (12, 14, 6),
 (11, 15, 5),
 (10, 16, 4),
 (9, 17, 3),
 (8, 18, 2),
 (7, 19, 1),
 (6, 20, None),
 (5, 21, None),
 (4, 22, None),
 (3, 23, None),
 (2, 24, None),
 (1, 25, None)]

答案 1 :(得分:1)

setA = [(1, 25), (2, 24), (3, 23), (4, 22), (5, 21), (6, 20), 
         (7, 19), (8, 18), (9, 17), (10, 16), (11, 15), (12, 14), 
         (13, 13),(14, 12), (15, 11), (16, 10), (17, 9), (18, 8), 
         (19, 7),(20, 6), (21, 5), (22, 4), (23, 3), (24, 2), (25, 1)]

setB = [(1, 19), (2, 18), (3, 17), (4, 16), (5, 15), (6, 14), (7, 13),
         (8, 12), (9, 11), (10, 10), (11, 9), (12, 8), (13, 7), (14, 6),
         (15, 5), (16, 4), (17, 3), (18, 2), (19, 1)]
la, lb = len(setA), len(setB)
temp=[[setA[i][1] if i<la else None, i+1, setB[i][1] if i<lb else None] for i in range(0,max(la,lb))]
[[25, 1, 19],
 [24, 2, 18],
 [23, 3, 17],
 [22, 4, 16],
 [21, 5, 15],
 [20, 6, 14],
 [19, 7, 13],
 [18, 8, 12],
 [17, 9, 11],
 [16, 10, 10],
 [15, 11, 9],
 [14, 12, 8],
 [13, 13, 7],
 [12, 14, 6],
 [11, 15, 5],
 [10, 16, 4],
 [9, 17, 3],
 [8, 18, 2],
 [7, 19, 1],
 [6, 20, None],
 [5, 21, None],
 [4, 22, None],
 [3, 23, None],
 [2, 24, None],
 [1, 25, None]]