索引和列表-索引超出范围

时间:2019-03-22 00:31:53

标签: python list

以下代码是否应打印? 100 100

price = 100  # assigns 'price' reference to 100
price = [price] # creates a 'price' list with 1 element: [100]

for i in range(1, 3):
    print(price[0]) # prints 100
    price[i] = price[i - 1]
    price.append(price[i])
    print(price[i])

在行IndexError: list assignment index out of range处出现price[i] = price[i - 1]错误,但前一行成功打印了100。价格[i]是否应该简单地分配给价格[0]?

5 个答案:

答案 0 :(得分:2)

您正在尝试将项目追加到列表中,或更准确地说,是使用某些重复的内容初始化列表。这是Pythonic的方法:

# Use a list comprehension
>>> price = [100 for _ in range(3)]
[100, 100, 100]

# Use itertools.repeat
>>> import itertools
>>> list(itertools.repeat(100, 3))
[100, 100, 100]

这两个方法都比(反复)执行append()(O(N))要快,因此重复执行append()就是长列表上的O(N ^ 2),这会非常慢。

(顺便说一句,如果您知道先验列表将至少包含N个元素,并且N大,则可以将其初始化为price = [None] * N并得到[None, None, None...]。现在,您可以直接将其分配给它们。但是,对于初学者,明确地执行添加是更好的做法。)

答案 1 :(得分:0)

如果您只是尝试追加到列表中,则尝试使用索引执行此操作将无法正常工作,因为该索引不存在于列表中:

somelist = []
somelist[0] = 1
IndexError

所以只需使用append

for i in range(1,3):
    price.append(price[i-1])

答案 2 :(得分:0)

问题是您分配的索引对于数组的长度而言太大。

  

对于范围在(1,3)中的i:

这会将i初始化为1。由于数组是零索引的,并且数组的长度在第一遍为1,所以您将在提到的行中击中assignment out of range error(当i=1时) )。

以下是显示问题的最小示例:

my_array = ["foo"]
my_array[1] = "bar" # throws assignment out of range error

答案 3 :(得分:0)

您不能直接为列表分配值,原因是该列表已记录了先前的大小。您必须使用append将元素添加到所需位置。

检查:

# Check the value on our initial position
print(price[0])
for i in range(1, 3):
    price.append(price[i-1])
    print(price[i])

答案 4 :(得分:0)

那不会打印出来:

100

100

您使用1个元素初始化了一个列表,该列表的大小为1。但是对于for循环,您的范围从1开始,实际上是:

price = 100  # assigns 'price' to 100
price = [price] # creates a 'price' list with 1 element: [100]

for i in range(1, 3): # The list is 0-indexed, meaning price[0] contains 100
    print(price[0]) # prints 100 as it should
    price[i] = price[i - 1] # i is 1, price[i] is not an assigned value, i.e: you never assigned price[1]
    price.append(price[i]) # This doesn't execute because an exception was thrown
    print(price[i]) # Neither does this

要获得所需的结果,这可以起作用:

price = [100] # creates a 'price' list with 1 element: [100]

for i in range(0, 2): # Start at index 0
    print(price[i]) # Print current index
    price.append(price[i]) # Append current value of price[i] to the price list

要确保所有内容都按您的预期进行,您可以使用len进行测试:

print(len(price))

Output:3

但是,这是@smci在其答案中显示的首选附加方式。