ValueError:解压缩的值太多(预期2)

时间:2014-06-10 21:15:12

标签: python input iterable-unpacking

在我正在使用的Python教程书中,我输入了一个给出同时分配的示例。我在运行程序时得到了前面提到的ValueError,并且无法找出原因。

以下是代码:

#avg2.py
#A simple program to average two exam scores
#Illustrates use of multiple input

def main():
    print("This program computes the average of two exam scores.")

    score1, score2 = input("Enter two scores separated by a comma: ")
    average = (int(score1) + int(score2)) / 2.0

    print("The average of the scores is:", average)

main()

这是输出。

>>> import avg2
This program computes the average of two exam scores.
Enter two scores separated by a comma: 69, 87
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    import avg2
  File "C:\Python34\avg2.py", line 13, in <module>
    main()
  File "C:\Python34\avg2.py", line 8, in main
    score1, score2 = input("Enter two scores separated by a comma: ")
ValueError: too many values to unpack (expected 2)

4 个答案:

答案 0 :(得分:7)

根据提示信息判断,您忘记在第8行末尾拨打str.split

score1, score2 = input("Enter two scores separated by a comma: ").split(",")
#                                                                ^^^^^^^^^^^

这样做会在逗号上拆分输入。请参阅下面的演示:

>>> input("Enter two scores separated by a comma: ").split(",")
Enter two scores separated by a comma: 10,20
['10', '20']
>>> score1, score2 = input("Enter two scores separated by a comma: ").split(",")
Enter two scores separated by a comma: 10,20
>>> score1
'10'
>>> score2
'20'
>>>

答案 1 :(得分:3)

上面的代码在Python 2.x上运行正常。因为input表现为raw_input,后面是Python 2.x上的eval,如此处所述 - https://docs.python.org/2/library/functions.html#input

但是,上面的代码会引发您在Python 3.x中提到的错误。在Python 3.x上,您可以在用户输入上使用ast模块的literal_eval()方法。

这就是我的意思:

import ast

def main():
    print("This program computes the average of two exam scores.")

    score1, score2 = ast.literal_eval(input("Enter two scores separated by a comma: "))
    average = (int(score1) + int(score2)) / 2.0

    print("The average of the scores is:", average)

main()

答案 2 :(得分:0)

这是因为输入的行为在python3

中发生了变化

在python2.7中输入返回值,你的程序在这个版本中工作正常

但是在python3中输入返回字符串

试试这个,它会正常工作!

score1, score2 = eval(input("Enter two scores separated by a comma: "))

答案 3 :(得分:0)

这意味着你的函数会返回更多的价值!

例如:

在python2中,函数cv2.findContours()返回 - &gt; contours, hierarchy

但是在python3 findContours(image, mode, method[, contours[, hierarchy[, offset]]]) -> image, contours, hierarchy

所以当你使用那些函数时,contours, hierachy = cv2.findContours(...)很好用python2,但在python3函数中返回3值为2变量。

SO ValueError:解压缩的值太多(预期为2)