【问题标题】:ValueError: too many values to unpack: python list manipulationValueError:要解包的值太多:python 列表操作
【发布时间】:2018-07-14 13:43:44
【问题描述】:

我在 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:解包的值太多

【问题讨论】:

  • 您的l 是一个列表列表。所以for x, y 是错误的。你想zip 两个列表。
  • 别那样做,answer = [list(tup) for tup in zip(*l)] 足以给你答案。

标签: python


【解决方案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)]

【讨论】:

  • 你的解决方案更pythonic
【解决方案2】:

使用标准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])])

【讨论】:

    【解决方案3】:

    您也可以尝试以下方法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多