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

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

ValueError while enumerating list

问题

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

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

我遇到以下错误:

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

我希望以下输出:

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

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

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

I am getting following error:

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

&gt; 

I want the following output:

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

答案1

得分: 1

解压索引和值分别。

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

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

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

Unpack the index and the values separately.

for index, (first, second, third) in enumerate(buttons):
    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.

for index, value in enumerate(buttons):
    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:

确定