ValueError:太多值无法解包:python列表操作

时间:2018-07-14 05:31:39

标签: python

我在python中有一个列表

l= [[1105.46, 1105.75, 1105.75, 1105.46, 1051.46],
 [ 120.23,  120.23,  120.41,  20.41,  120.23]]

我怎么能得到这个?

answer = [[1105.46,120.23], ....[1051.46,120.23]]

我是这样的:

answer = [[x, y] for x, y in l]
print answer

ValueError:太多值无法解包

3 个答案:

答案 0 :(得分:6)

这是一种简单的方法:

>>> map(list, zip(*l))
[[1105.46, 120.23], [1105.75, 120.23], [1105.75, 120.41], [1105.46, 20.41], [1051.46, 120.23]]

如果您不在乎嵌套元素是列表还是元组,则更为简单:

>>> zip(*l)
[(1105.46, 120.23), (1105.75, 120.23), (1105.75, 120.41), (1105.46, 20.41), (1051.46, 120.23)]

答案 1 :(得分:1)

使用标准python中的zip()函数:

l= [[1105.46, 1105.75, 1105.75, 1105.46, 1051.46],
 [ 120.23,  120.23,  120.41,  20.41,  120.23]]

new_list = []
for x, y in zip(l[0], l[1]):
    new_list.append([x, y])

print(new_list)

输出:

[[1105.46, 120.23], [1105.75, 120.23], [1105.75, 120.41], [1105.46, 20.41], [1051.46, 120.23]]

具有列表理解功能的单行版本:

print([[x, y] for x, y in zip(l[0], l[1])])

答案 2 :(得分:1)

您也可以尝试以下方法。

>>> l = [[1105.46, 1105.75, 1105.75, 1105.46, 1051.46], [ 120.23,  120.23,  120.41,  20.41,  120.23]]
>>>
>>> answer = [list(tup) for tup in zip(*l)]
>>>
>>> answer
[[1105.46, 120.23], [1105.75, 120.23], [1105.75, 120.41], [1105.46, 20.41], [1051.46, 120.23]]
>>>