【问题标题】:i am getting need more than one value to unpack value error [duplicate]我需要多个值来解压值错误 [重复]
【发布时间】:2016-08-18 01:46:14
【问题描述】:

这是我的程序

from sys import argv
script, first, second, third = argv
print ("the script is:", script)
print("the first variable is:", first)
print("the second variable is:", second)
print ("the third variable is:", third)

错误是:

Traceback (most recent call last):
  File "C:/Users/ravikishore/PycharmProjects/Test/.idea/MyPython.py", line 2, in <module>
    [script, first, second, third] = argv
ValueError: need more than 1 value to unpack

【问题讨论】:

  • 我链接到的副本不仅与您遇到的问题相同,而且是同一教程中的相同练习。
  • 顺便说一句,请注意许多 Python 程序员不推荐Learn Python the Hard Way。它有many problems,还有better free tutorials可供选择。如果您不想切换,至少要记住 还有 其他教程,所以如果 LPtHW 中的概念没有意义,您可以阅读其他解释,看看它们是否对你更有意义。

标签: python


【解决方案1】:

argv 是一个列表:

>>> from sys import argv
>>> type(argv)
<type 'list'>

因此,您正在尝试从列表转换为元组,这仅在元组中的元素数量完全与列表长度匹配时才有效:

>>> a,b,c = [1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
>>> a,b,c = [1,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack
>>> a,b,c = [1,2,3]
>>> a,b,c = [1,2,3,4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

因此,在尝试转换之前,您需要对 argv 长度添加一些检查。

【讨论】:

    【解决方案2】:

    该代码正常工作,假设您实际上给三个参数来解包,如下所示:

    c:\pax> python yourProg.py A B C
    the script is: yourProg.py
    the first variable is: A
    the second variable is: B
    the third variable is: C
    

    当您没有给它足够的参数时,就会出现问题:

    c:\pax> python yourProg.py A
    Traceback (most recent call last):
      File "yourProg.py", line 2, in <module>
        script, first, second, third = argv
    ValueError: not enough values to unpack (expected 4, got 2)
    

    如果您想在尝试解包之前确保有足够的参数,可以使用len(argv) 获取参数计数,并将其与您需要的值进行比较,例如:

    import sys
    if len(sys.argv) != 4:
        print("Need three arguments after script name")
        sys.exit(1)
    script, first, second, third = sys.argv
    print ("the script is:", script)
    print("the first variable is:", first)
    print("the second variable is:", second)
    print ("the third variable is:", third)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      相关资源
      最近更新 更多