python - 值错误: need more than 0 values to unpack(python lists)

标签 python sequencing

我在编写代码时遇到错误

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/

相关文章:

javascript - Python 将 2 组数据放入 JSON 对象中以进行 ajax 响应

c++ - int a =++i+++i 是未定义的行为吗?

c++ - 对函数参数的要求是否也适用于初始化列表?

bioinformatics - 运行 bowtie2 时 breseq 出错

python - 通过 Python 中的 c 函数传递和返回 double 组

python - 错误的合并排序

Python mysql-connector 将一些字符串转成bytearray

distributed-computing - Messenger 如何在聊天期间和用户再次登录时保持消息的顺序?

python - Pandas 将行合并并转换为列以及特征工程