数值错误:解包的值过多(期望为2个)

11
在我使用的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)

可能是Python ValueError: too many values to unpack的重复问题。 - Leb
这是因为你正在使用Python3,请检查我的答案,它可能会对你有所帮助 :) - DexJ
4个回答

11
根据提示信息,第八行末尾你忘记调用 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'
>>>

4
上述代码在Python 2.x上可以正常工作。因为在Python 2.x中,input的行为与此处所述的一样,相当于raw_input后跟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()

哦,从来没有考虑过用 literal_eval 来做那件事! - kindall

0

这意味着您的函数返回更多的值!

例如:

在Python2中,cv2.findContours() 函数返回 --> contours, hierarchy

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

因此当您使用这些函数时,contours, hierachy = cv2.findContours(...) 在Python2中可用,但是在Python3中,该函数会返回3个值到2个变量。

SO ValueError: too many values to unpack (expected 2)


0

这是因为在Python3中输入的行为发生了改变

在Python2.7中,输入返回值,您的程序在此版本中运行良好

但在Python3中,输入返回字符串

尝试这个方法,它会正常工作!

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接