ValueError: need more than 0 values to unpack(python lists)

ValueError: need more than 0 values to unpack(python lists)

我在编写代码时遇到错误

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 认为您要将列表的第一项分配给您的 variable.Likewise 时,当您使用代码 [first, last] = [1,2] 时,则变量 first 赋值 1,变量 last 赋值 2。这称为解包。

此外,在 [index].append(2) 中,您不应在变量名称两边使用方括号。这不会引发任何错误,但它会做的是创建一个新列表(唯一的项目是 index 的值),然后在该行执行后销毁列表。

您的代码应如下所示(假设代码的其他部分是正确的)。此外,正如 建议的那样,使用 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,我认为他的意思是将索引用作整数。此外,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)