[英]ValueError: too many values to unpack (expected 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)
根据提示信息判断,您忘记在第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'
>>>
上面的代码在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()
这是因为输入的行为在python3中发生了变化
在python2.7中输入返回值,你的程序在这个版本中正常工作
但是在python3中输入返回字符串
试试这个,它会工作正常!
score1, score2 = eval(input("Enter two scores separated by a comma: "))
这意味着你的功能会带来更多价值!
例如:
在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:解压缩的值太多(预期2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.