【问题标题】:Python3 ValueError - Too many values to unpack while iterating over a listPython3 ValueError - 迭代列表时解包的值太多
【发布时间】:2021-06-24 12:27:27
【问题描述】:

这是一个简单的代码,旨在使用英语名字和姓氏列表生成全名列表:

names = """
Walter
Dave
Albert""".split()

fullnames = [(first + last) for first, last in names]
print(fullnames)

为了这篇文章,我缩小了names,但我包含了 100 个名字。

输出:

Traceback (most recent call last):
  File "/home/pussyslayer42069/Desktop/py/names.py", line 105, in <module>
    fullnames = [(first + last) for first, last in names]
  File "/home/pussyslayer42069/Desktop/py/names.py", line 105, in <listcomp>
    fullnames = [(first + last) for first, last in names]
ValueError: too many values to unpack (expected 2)

【问题讨论】:

  • 请添加您想要的输出,因为不清楚您想要什么。你为什么要这样拆清单??
  • 将“Walter”分配给first,将“Dave”分配给last,“Water Dave”。 @irfanwani
  • Names 是一个列表,所以当你遍历它时,每次只有一个值。您正在尝试获取 2 个值 - 第一个和最后一个。
  • 那么您希望结果为 ["Walter Dave", "Dave Albert"] 还是 ["Walter Dave", "Albert (and next name)"]。

标签: python python-3.x valueerror list-manipulation


【解决方案1】:

如果我找到你,这里就是解决方案;

names = """
Walter
Dave
Albert""".split()


fullnames = [(names[i] + ' ' + names[i + 1]) for i in range(len(names) - 1)]
print(fullnames)

【讨论】:

    【解决方案2】:

    使用zip 并遍历列表的两个切片

    [(f, l) for f, l in zip(names[:-1], names[1:]]

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2017-04-30
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      • 2012-02-15
      相关资源
      最近更新 更多