值错误:解包时值过多(预期2个)
在我正在使用的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 个回答
这意味着你的函数返回了更多的值!
举个例子:
在Python 2中,函数 cv2.findContours()
返回的是 contours, hierarchy
。
但是在Python 3中, findContours(image, mode, method[, contours[, hierarchy[, offset]]])
返回的是 image, contours, hierarchy
。
所以当你使用这个函数时,在Python 2中可以这样写: contours, hierarchy = cv2.findContours(...)
,这没问题。但在Python 3中,函数返回了3个值,而你只用2个变量来接收。
因此会出现错误:ValueError: too many values to unpack (expected 2),意思是你试图接收的值太多了,预期只需要2个。
这是因为在Python 3中,输入的行为发生了变化。
在Python 2.7中,输入会返回一个值,所以你的程序在这个版本中运行得很好。
但是在Python 3中,输入会返回一个字符串。
试试这个,应该就能正常工作了!
score1, score2 = eval(input("Enter two scores separated by a comma: "))
上面的代码在 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()
根据提示信息来看,你在第八行的最后忘记调用了 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'
>>>