我在编写代码时遇到错误
tmp = c.pop(0) # taking out the first element from the list as the starting point
complete = tmp[0][-1]
print(complete)
while c != []:
complete += tmp[1][-1]
[index] = []
for i, pair in enumerate(c):
if pair[0] == tmp[1]:
[index].append(i)
temp = c.pop(index)
print(complete)
我在 [index] == []
部分收到此错误:
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
我的问题是,为什么会出现此错误以及我应该如何解决此问题?
最佳答案
在Python中,即使变量包含列表,也应该将其用作常规变量,如index = []
。当你使用[index] = []
时,Python认为你想要将列表的第一项分配给你的变量。同样,当你使用代码[first, last] = [1 ,2]
,则变量first
被赋值1,变量last
被赋值2。这称为拆包。
此外,在[index].append(2)
中,不应在变量名称两边使用方括号。这不会引发任何错误,但它会创建一个新列表(唯一的项目是 index
的值),然后在该行执行后销毁该列表。
您的代码应如下所示(假设代码的其他部分正确)。另外,如this comment建议使用 c
而不是 c != []
因为空列表是错误的并且它遵循 Python 约定。 :
tmp = c.pop(0) # taking out the first element from the list as the starting point
complete = tmp[0][-1]
print(complete)
while c: # c != []
complete += tmp[1][-1]
index = [] # [index] = []
for i, pair in enumerate(c):
if pair[0] == tmp[1]:
index.append(i) # [index].append(i)
temp = c.pop(index)
print(complete)
如注释中所述,temp = c.pop(index)
行将给出错误,因为 pop 需要一个整数,而代码给它一个列表。
但是,由于OP在代码中使用了index
,我认为他的意思是使用index作为整数。此外,OP 指出使用 temp
而不是 tmp
是一个错误。
tmp = c.pop(0) # taking out the first element from the list as the starting point
complete = tmp[0][-1]
print(complete)
while c:
complete += tmp[1][-1]
index = 0
for i, pair in enumerate(c):
if pair[0] == tmp[1]:
index = i
tmp = c.pop(index)
print(complete)
关于python - 值错误: need more than 0 values to unpack(python lists),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29584964/