Python 中的 ValueError: Not Enough Values to Unpack
当你刚开始接触Python编程时,这是一个常见的错误,或者有时它可能是一个类型错误,你提供了更多的值,但更少的变量(容器)来捕获这些值。或者当你试图遍历字典的值或键,但同时访问两者时。
本文将详细介绍每个场景沿着示例,但在此之前,让我们了解一下Python中的ValueError
是什么。
在Python中什么是 ValueError
ValueError
是Python中的一个常见异常,当值的数量与接受输入、直接赋值或通过数组或访问受限值的变量的数量不匹配时会发生。为了理解#2,让我们举个例子。
# this input statement expects three values as input
x,y,z = input("Enter values for x, y and z: ").split(",")
输出:
Enter values for x, y and z: 1,2
ValueError: not enough values to unpack (expected 3, got 2)
在上面的例子中,我们有三个变量x,y,z
来捕获输入值,但是我们提供了两个输入值来演示ValueError
。
现在input
语句有三个值,由于用户输入的值不满足预期条件,它抛出ValueError: not enough values to unpack (expected 3, got 2)
。
错误本身是不言自明的;它告诉我们期望的值的数量是3,但您提供了2。
ValueError
的其他一些常见原因可能如下。
a,b,c = 3, 5 #ValueError: not enough values to unpack (expected 3, got 2)
a,b,c = 2 #ValueError: not enough values to unpack (expected 3, got 1)
a,b,d,e = [1,2,3] #ValueError: not enough values to unpack (expected 4, got 3)
Python字典中修复 ValueError: not enough values to unpack
在Python中,字典是另一种数据结构,它的元素是键-值对,每个键都应该有一个对应的值,你可以用它们的键访问值。
Python中字典的语法:
student = {
"name" : "Zeeshan Afridi",
"degree" : "BSSE",
"section" : "A"
}
这是字典的一般结构;左边的值是键,而其它的是键的值。
我们已经为Python指定了函数,例如keys()
,values()
,items()
等字典。但这些是循环遍历字典的最常见和最有用的函数。
print("Keys of Student dictionary: ", student.keys())
print("Values of Student dictionary: ", student.values())
print("Items of Student dictionary: ", student.items())
输出:
Keys of Student dictionary: dict_keys(['name', 'degree', 'section'])
Values of Student dictionary: dict_values(['Zeeshan Afridi', 'BSSE', 'A'])
Items of Student dictionary: dict_items([('name', 'Zeeshan Afridi'), ('degree', 'BSSE'), ('section', 'A')])
让我们来看看为什么ValueError: not enough values to unpack
会出现在Python字典中。
student = {
#Keys : Values
"name" : "Zeeshan Afridi",
"degree" : "BSSE",
"section" : "A"
}
#iterate user dictionary
for k,v,l in student.items(): # This statement throws an error
print("Key:", k)
print("Value:", str(v))
输出:
ValueError: not enough values to unpack (expected 3, got 2)
正如你所看到的,上面的代码抛出了一个错误,因为.items()
函数期望两个变量来捕获student
字典的键和值,但我们提供了三个变量k,v,l
。
所以在l
字典中没有student
的空间,它抛出了ValueError: not enough values to unpack (expected 3, got 2)
。
要解决这个问题,您需要修复字典的变量。
for k,v in student.items()
这是在Python中迭代字典的正确语句。
在Python中修复 ValueError: not enough values to unpack
为了避免Python中的此类异常,您应该为变量提供预期数量的值,并显示有用的消息,以便在向表单或任何文本字段中输入数据时提供指导。
除此之外,您可以使用try-catch
块在程序崩溃之前捕获此类错误。
让我们了解如何修复Python中的ValueError: not enough values to unpack
。
# User message --> Enter three numbers to multiply ::
x,y,z = input("Enter three numbers to multiply :: ").split(",")
# type casting x,y, and z
x = int(x)
y = int(y)
z = int(z)
prod = (x*y*z)
print("The product of x,y and z is :: ",prod)
输出:
Enter three numbers to multiply :: 2,2,2
The product of x,y and z is :: 8
在这个例子中,input
语句期望三个输入,我们已经提供了期望的输入数量,所以它没有抛出任何ValueError
。