索引超出范围错误,这是不应该发生的

时间:2022-12-30 16:43:26

I am trying to get these 4 decimal numbers and convert them into binary and store them into list. and I get index out of range error.. what seems to be the problem? I tried to put them in the list not using for loop too. but didn't work

我想获取这4个十进制数并将它们转换为二进制并将它们存储到列表中。我得到索引超出范围错误..什么似乎是问题?我试着将它们放在列表中,而不是使用for循环。但没有奏效

value = [128, 12, 1, 1]
binary = []
i = 0
for x in value:
    binary[i] = bin(x)
    i += 1

2 个解决方案

#1


You cannot increase the size of a list by assigning to indices beyond the end of the list. Use the append method instead.

您不能通过分配超出列表末尾的索引来增加列表的大小。请改用append方法。

value = [128, 12, 1, 1]
binary = []
for x in value:
    binary.append(x)

(Even better is to use a list comprehension, if possible, although that depends on what you actually do with the value of x before appending to binary. The code you show really simplifies to binary = list(value).)

(更好的是使用列表推导,如果可能的话,虽然这取决于你在追加到二进制文件之前对x的值实际做了什么。你显示的代码实际上简化为binary = list(value)。)

#2


I think this is what you are looking for:

我认为这就是你要找的东西:

value = [128, 12, 1, 1]
binary = [bin(x) for x in value]

#1


You cannot increase the size of a list by assigning to indices beyond the end of the list. Use the append method instead.

您不能通过分配超出列表末尾的索引来增加列表的大小。请改用append方法。

value = [128, 12, 1, 1]
binary = []
for x in value:
    binary.append(x)

(Even better is to use a list comprehension, if possible, although that depends on what you actually do with the value of x before appending to binary. The code you show really simplifies to binary = list(value).)

(更好的是使用列表推导,如果可能的话,虽然这取决于你在追加到二进制文件之前对x的值实际做了什么。你显示的代码实际上简化为binary = list(value)。)

#2


I think this is what you are looking for:

我认为这就是你要找的东西:

value = [128, 12, 1, 1]
binary = [bin(x) for x in value]