“ValueError while enumerating list” 中文翻译:在枚举列表时发生数值错误。

huangapple go评论83阅读模式
英文:

ValueError while enumerating list

问题

我正在尝试使用以下代码在列表前面添加索引号,使用enumerate:

  1. buttons = [('John', 'Sen', 'Morro'), ('Lin', 'Ajay', 'Filip')]
  2. for first, second, third in enumerate(buttons):
  3. print(first, second, third)

我遇到以下错误:

  1. Traceback (most recent call last):
  2. File "<string>", line 2, in <module>
  3. ValueError: not enough values to unpack (expected 3, got 2)

我希望以下输出:

  1. 0 ('John', 'Sen', 'Morro')
  2. 1 ('Lin', 'Ajay', 'Filip')
英文:

I am trying to add index number in front of the list using enumerate with the following code:

  1. buttons = [(&#39;John&#39;, &#39;Sen&#39;, &#39;Morro&#39;), (&#39;Lin&#39;, &#39;Ajay&#39;, &#39;Filip&#39;)]
  2. for first, second, third in enumerate(buttons):
  3. print(first, second, third)

I am getting following error:

  1. Traceback (most recent call last):
  2. File &quot;&lt;string&gt;&quot;, line 2, in &lt;module&gt;
  3. ValueError: not enough values to unpack (expected 3, got 2)
  4. &gt;

I want the following output:

  1. 0 (&#39;John&#39;, &#39;Sen&#39;, &#39;Morro&#39;)
  2. 1 (&#39;Lin&#39;, &#39;Ajay&#39;, &#39;Filip&#39;)

答案1

得分: 1

解压索引和值分别。

  1. for index, (first, second, third) in enumerate(buttons):
  2. print(index, first, second, third)

如果你不打算访问它们的值,你不需要解压原始列表的每个元素。

  1. for index, value in enumerate(buttons):
  2. print(index, value)
英文:

Unpack the index and the values separately.

  1. for index, (first, second, third) in enumerate(buttons):
  2. print(index, first, second, third)

You don't need to unpack each element of the original list if you're not going to access their values anyway.

  1. for index, value in enumerate(buttons):
  2. print(index, value)

huangapple
  • 本文由 发表于 2023年4月11日 04:29:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定