【发布时间】:2020-09-19 06:35:38
【问题描述】:
我有一个 x 和 y 坐标的元组列表,例如: [(1,2), (3,4), (5,6)] 我想操纵列表成为一个 2xN 矩阵(取决于有多少数字),这样我就有一个只有 x 坐标和 y 坐标的列表。基本上我想输出: [(1,3,5), (2,4,6)] 通过一个函数,但不完全确定如何这样做。
【问题讨论】:
标签: python list matrix tuples concatenation
我有一个 x 和 y 坐标的元组列表,例如: [(1,2), (3,4), (5,6)] 我想操纵列表成为一个 2xN 矩阵(取决于有多少数字),这样我就有一个只有 x 坐标和 y 坐标的列表。基本上我想输出: [(1,3,5), (2,4,6)] 通过一个函数,但不完全确定如何这样做。
【问题讨论】:
标签: python list matrix tuples concatenation
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.
【讨论】:
(a, b), (c, d), (e, f)“转换”为(a, c, e), (b, d, f)。