首页 > 解决方案 > 我想在python中组合一个元组列表

问题描述

我有一个 x 和 y 坐标的元组列表,例如: [(1,2), (3,4), (5,6)] 我想操纵该列表成为一个 2xN 矩阵(取决于有多少数字),这样我就有了一个只有 x 坐标和 y 坐标的列表。基本上我想通过一个函数输出: [(1,3,5), (2,4,6)] ,但不完全确定该怎么做。

标签: pythonlistmatrixtuplesconcatenation

解决方案


list(zip(*[(1, 2), (3, 4), (5, 6)]))

将输出:

[(1, 3, 5), (2, 4, 6)]

>>> a = [(1, 2), (3, 4), (5, 6)]

>>> zip(*a) # Returns a zipped object. 
<zip object at 0x10c9f5540>

>>> print(*a) # "Star a" unpacks the list.
(1, 2) (3, 4) (5, 6)

>>> print(a[0], a[1], a[2]) # Above is equivalent to:
(1, 2) (3, 4) (5, 6)

>>> b, c = [1, 2], [3, 4]

>>> list(zip(b, c))
[(1, 3), (2, 4)] # Zips the inputs of both lists in the pattern (b1, c1) and (b2, c2). list() converts the "zip" generator to a list. 

>>> list(zip(*a)) 
[(1, 3, 5), (2, 4, 6)] # Zips the wanted ints with the logic above.

推荐阅读