Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ValueError:要解压缩的值太多:python列表操作_Python - Fatal编程技术网

ValueError:要解压缩的值太多:python列表操作

ValueError:要解压缩的值太多:python列表操作,python,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:使用标准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:使用标准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])])

这里有一个简单的方法:

>>> 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)]

您也可以尝试以下方法

>>> 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]]
>>>

您的
l
是一个列表列表。因此x,y的
是错误的。您希望
zip
两个列表。不要这样做,只要
answer=[list(tup)for tup in zip(*l)]
就足以给出答案。您的解决方案更具python风格