将元组列表重组为浮点数列表
假设我在 python 中有一个元组列表
list1 = [(1,1,1), (2,2,2), (3,3,3)]
如果我想将它们分成所有 1 个位置值、2 个位置值和 3 个位置值的列表,我会这样做:
ones = [tuple[0] for tuple in list1]
twos = [tuple[1] for tuple in list1]
threes = [tuple[2] for tuple in list1]
列表中每个元组的元素越多,这种方式就会变得非常麻烦。是否有一种更清洁的方法可以使用 zip 方法或相反的方法来做到这一点?
回答
您可以zip为此使用:
list(zip(*list1))
输出:
[(1, 2, 3), (1, 2, 3), (1, 2, 3)]
正如@paoloaq 所指出的,您可以将它们解压到单独的列表中:
ones, two, threes = list(zip(*list1))
或者如果你想要列表而不是元组:
ones, two, threes = map(list, list(zip(*list1)))
旁注:尽量避免像list和这样的变量名tuple。