为什么此迭代列表增长代码使IndexError:列表分配索引超出范围?

问题:为什么此迭代列表增长代码使IndexError:列表分配索引超出范围?

请考虑以下代码:

i = [1, 2, 3, 5, 8, 13]
j = []
k = 0

for l in i:
    j[k] = l
    k += 1

print j

输出(Win 7 32位上的Python 2.6.6)为:

> Traceback (most recent call last): 
>     j[k] = l IndexError: list assignment index out of range

我想这很简单,我不明白。有人可以清理吗?

Please consider the following code:

i = [1, 2, 3, 5, 8, 13]
j = []
k = 0

for l in i:
    j[k] = l
    k += 1

print j

The output (Python 2.6.6 on Win 7 32-bit) is:

> Traceback (most recent call last): 
>     j[k] = l IndexError: list assignment index out of range

I guess it’s something simple I don’t understand. Can someone clear it up?


回答 0

j是一个空列表,但您正在尝试[0]在第一次迭代中写入元素,但该迭代尚不存在。

请尝试以下操作,以将新元素添加到列表的末尾:

for l in i:
    j.append(l)

当然,如果您只想复制一个现有列表,则您永远都不会这样做。您只需:

j = list(i)

另外,如果您想像其他语言的数组一样使用Python列表,则可以预先创建一个列表,并将其元素设置为空值(None在下面的示例中),然后在特定位置覆盖值:

i = [1, 2, 3, 5, 8, 13]
j = [None] * len(i)
#j == [None, None, None, None, None, None]
k = 0

for l in i:
   j[k] = l
   k += 1

要实现的事情是,list对象将不允许您将值分配给不存在的索引。

j is an empty list, but you’re attempting to write to element [0] in the first iteration, which doesn’t exist yet.

Try the following instead, to add a new element to the end of the list:

for l in i:
    j.append(l)

Of course, you’d never do this in practice if all you wanted to do was to copy an existing list. You’d just do:

j = list(i)

Alternatively, if you wanted to use the Python list like an array in other languages, then you could pre-create a list with its elements set to a null value (None in the example below), and later, overwrite the values in specific positions:

i = [1, 2, 3, 5, 8, 13]
j = [None] * len(i)
#j == [None, None, None, None, None, None]
k = 0

for l in i:
   j[k] = l
   k += 1

The thing to realise is that a list object will not allow you to assign a value to an index that doesn’t exist.


回答 1

您的另一个选择是初始化j

j = [None] * len(i)

Your other option is to initialize j:

j = [None] * len(i)

回答 2

j.append(l)而不是j[k] = l避免k

Do j.append(l) instead of j[k] = l and avoid k at all.


回答 3

您还可以使用列表理解:

j = [l for l in i]

或使用以下语句进行复制:

j = i[:]

You could also use a list comprehension:

j = [l for l in i]

or make a copy of it using the statement:

j = i[:]

回答 4

j.append(l)

还要避免使用小写的“ L”,因为它们很容易与1混淆。

j.append(l)

Also avoid using lower-case “L’s” because it is easy for them to be confused with 1’s


回答 5

我认为您正在寻找Python方法插入项

在位置i处插入元素x。list.insert(i,x)

array = [1,2,3,4,5]

array.insert(1,20)

print(array)

# prints [1,2,20,3,4,5]

I think the Python method insert is what you’re looking for:

Inserts element x at position i. list.insert(i,x)

array = [1,2,3,4,5]

array.insert(1,20)

print(array)

# prints [1,2,20,3,4,5]

回答 6

您可以为j使用字典(类似于关联数组)

i = [1, 2, 3, 5, 8, 13]
j = {} #initiate as dictionary
k = 0

for l in i:
    j[k] = l
    k += 1

print j

将打印:

{0: 1, 1: 2, 2: 3, 3: 5, 4: 8, 5: 13}

You could use a dictionary (similar to an associative array) for j

i = [1, 2, 3, 5, 8, 13]
j = {} #initiate as dictionary
k = 0

for l in i:
    j[k] = l
    k += 1

print j

will print :

{0: 1, 1: 2, 2: 3, 3: 5, 4: 8, 5: 13}

回答 7

另一种方式:

j=i[0]
for k in range(1,len(i)):
    j = numpy.vstack([j,i[k]])

在这种情况下j将是一个numpy数组

One more way:

j=i[0]
for k in range(1,len(i)):
    j = numpy.vstack([j,i[k]])

In this case j will be a numpy array


回答 8

也许你需要extend()

i=[1,3,5,7]
j=[]
j.extend(i)

Maybe you need extend()

i=[1,3,5,7]
j=[]
j.extend(i)