Skip to content

ValueError: 不 enough 值到 unpack

错误信息

                不 enough 值到 unpack (expected 3, 获取 2)
              

快速摘要

你 tried 到 unpack 序列到 数字的 变量那个 doesn't match 序列's 长度.

为什么发生

  • Unpacking tuple/列表使用 fewer 元素 than 变量

  • Unpacking 字符串拆分 result 使用错误数字的 部分

  • Expecting 更多返回值 than 函数 provides

最小示例

✗ 错误代码
data = (1, 2)
a, b, c = data  # ValueError: not enough values to unpack
✓ 修复代码
data = (1, 2)
a, b = data  # Correct: 2 values, 2 variables
# Or use * for flexible unpacking:
# a, *rest = data

tuple 有 2 元素但 3 变量是 used. Match 变量数量到 序列长度.

如何诊断

  • 检查长度的 序列是 unpacked

  • 验证数字的 变量 matches 序列长度

  • Print 序列之前 unpacking 到 see 它的内容

如何修复

  • Match 数字的 变量到 序列长度

  • Use * 到 collect extra 值: , *REST = 序列

  • 检查长度之前 unpacking

如何预防

  • 验证序列长度之前 unpacking

  • Use * unpacking for 变量-长度序列

  • 测试使用 representative 数据

相关资源

相关术语

相关课程

← 返回语言