Python ValueError:太多的值无法解包,如何解决此问题?
所以我得到了“太多值无法解包错误”,我猜这是因为我试图将“u,u,pile1,pile2”设置为仅等于两个变量。但是我不明白为什么,既然我已经说过要忽略前两个变量,它不应该忽略这两个变量,然后将其余的设置为pile1,pile2吗Python ValueError:太多的值无法解包,如何解决此问题?,python,Python,所以我得到了“太多值无法解包错误”,我猜这是因为我试图将“u,u,pile1,pile2”设置为仅等于两个变量。但是我不明白为什么,既然我已经说过要忽略前两个变量,它不应该忽略这两个变量,然后将其余的设置为pile1,pile2吗 def getCompMove(x,y, pile1, pile2): print("Now it's my turn.") pile1, pile2= pile1, pile2 x= x y= y if x==1:
def getCompMove(x,y, pile1, pile2):
print("Now it's my turn.")
pile1, pile2= pile1, pile2
x= x
y= y
if x==1:
print("I, the champion chips computer will take "+str(y)+ " chips from pile 2")
pile2= pile2 - y
pile1= pile1
elif x==2:
print("I, the champion chips computer will take "+str(y)+ " chips from pile 1")
pile1= pile1 - y
pile2= pile2
return x,y, pile1, pile2
def compPiles(pile1, pile2):
print("Here are the piles: ")
pile1, pile2= pile1, pile2
print("pile 1: ", str(pile1))
print("pile 2: ", str(pile2))
return pile1, pile2
###########MAIN################
_,_,pile1, pile2 = getCompMove(x,y, pile1, pile2)
if pile1==0 and pile2==0:
print("The game is over because I took the last chip.")
print("Thanks for playing. Let's wager next time.")
pile1, pile2 = _,_,pile1, pile2
compi= compPiles(pile1, pile2)
我明白了
Traceback (most recent call last):
File "C:\Users\Yuya\Downloads\homework2.py", line 113, in <module>
pile1, pile2 = _,_,pile1, pile2
ValueError: too many values to unpack (expected 2)
回溯(最近一次呼叫最后一次):
文件“C:\Users\Yuya\Downloads\homework2.py”,第113行,在
第一排,第二排=u,u,第一排,第二排
ValueError:要解压缩的值太多(应为2个)
这一行是罪魁祸首:
pile1, pile2 = _,_,pile1, pile2
你在LHS上有两个东西,你正试图打开四个。你不能那样做,但你的目标不明确。问题的解决方案需要更好地描述它
请注意,在此上下文中,\uu
与任何其他*一样是一个变量。所以当你说
_,_,pile1, pile2 = getCompMove(x,y, pile1, pile2)
您正在读取元组中的第一个值,然后是由getCompMove
返回到\uu
中的第二个值。最终结果是,\uu
保存第二个值。所以当你这么说的时候:
pile1, pile2 = _,_,pile1, pile2
您只是试图将四个值读入两个变量,错误告诉您,这是无效的。您所做的与此等效:
x, x, y, z = 1, 2, 3, 4
a, b = x, x, y, z
*尽管它在python交互式解释器中有特殊用途:最后一个表达式的求值结果,但实际上不需要这一行:
pile1, pile2 = _,_,pile1, pile2
您的代码如下所示:
_,_,pile1, pile2 = getCompMove(x,y, pile1, pile2)
if pile1==0 and pile2==0:
print("The game is over because I took the last chip.")
print("Thanks for playing. Let's wager next time.")
compi= compPiles(pile1, pile2)
那一行的目的是什么?为什么你要把
pile
和pile2
设置为它们自己?这不会有任何效果。x
和y
显然与getCompMove
无关;你为什么要返回它们?!还有,为什么要费心于例如pile2=pile2
,或者将compPiles
将返回到compi
的None
赋值呢?实际上,您只丢弃了函数调用返回的第一个值。第二个存储在.
@juanchopanza中,我刚刚试过,你说得对。这是如何工作的?\uu
只是另一个变量名,所以它就像说x,x,y,z=1,2,3,4
。说“我不需要使用这个值”是一种惯例,但实际上你可以使用它。尽管要小心:ipython
对有特殊用途。对不起,我应该知道的。只是编辑了它,以便有更多的信息。@TheAznHawk它对我没有帮助,但我添加了一些解释,希望能帮助你理解发生了什么。是的,对不起。我对python和一般编程都是新手。我已经为此工作了好几个小时,沮丧真的堆积起来了,哈哈。但是谢谢你帮我解决了这个问题。