You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用enumerate为列表添加索引时触发ValueError错误的求助

enumerate解包错误修复

你的代码报错是因为对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 "", line 2, in
ValueError: not enough values to unpack (expected 3, got 2)

错误原因

enumerate()遍历可迭代对象时,每次返回的是**(索引值, 当前元素)**的二元组,你试图把这两个值拆成三个变量,因此触发了解包数量不匹配的错误。

正确代码

要得到你期望的输出,只需把迭代项拆成索引和完整的元组元素即可:

buttons = [('John', 'Sen', 'Morro'), ('Lin', 'Ajay', 'Filip')] 
for idx, item in enumerate(buttons):
    print(idx, item)

运行后输出:

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

内容的提问来源于stack exchange,提问作者urvi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 03:22:52