【问题标题】:value error: not enough value to unpack in python [duplicate]值错误:没有足够的值在 python 中解压 [重复]
【发布时间】:2020-08-03 15:22:36
【问题描述】:

我正在使用 Learning Python the Hard Way。在我的学习过程中,我遇到了这个错误。虽然我从昨天开始就一直在尝试调试,但我做不到。 这是我的代码:

import sys
from sys import argv

script, first, second = argv
print('the script is called:', script)
print('the first variable is:', first)
print('the second vriable is:', second)
print('the third variable is:', third)

【问题讨论】:

标签: python


【解决方案1】:

您遇到的错误意味着您试图将可迭代的 (list, tuple) 解构为比实际列表中更多的值。如果你要跑步

print(argv, len(argv))

您可能会看到argv 中没有三个变量。

argv 显示您在运行脚本时提供的参数。例如,如果我跑:

python test_args.py

我只会收到:['test_args.py'] 作为我的argv 变量。如果我尝试提供更多参数,例如:

python test_args.py a b

然后我的 argv 看起来像:['test_args.py', 'a', 'b']。您的代码完全取决于您在运行它时传递了多少参数,因此也请自行调整以更好地了解正在发生的事情。

【讨论】:

  • 哦,很好,现在取得了进展,谢谢
【解决方案2】:

我想你正在以这种格式执行脚本

python script.py 10 20

问题是您使用了一个未初始化的额外变量third。 如果你真的想要 3 个参数,那么你必须在执行时传递三个值,如下所示。

python script.py 10 20 30

然后改代码如下。

from sys import argv

script, first, second, third = argv
print('the script is called:', script)
print('the first variable is:', first)
print('the second vriable is:', second)
print('the third variable is:', third)

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    相关资源
    最近更新 更多