英文:
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 = [('John', 'Sen', 'Morro'), ('Lin', 'Ajay', 'Filip')]
for first, second, third in enumerate(buttons):
print(first, second, third)
I am getting following error:
Traceback (most recent call last):
File "<string>", line 2, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
>
I want the following output:
0 ('John', 'Sen', 'Morro')
1 ('Lin', 'Ajay', 'Filip')
答案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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论