本文介绍了为什么这个迭代的列表增长代码会给出 IndexError: list assignment index out of range?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

请考虑以下代码:

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)是:

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?

推荐答案

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

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)

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

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

要意识到的是,list 对象不允许您为不存在的索引分配值.

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

这篇关于为什么这个迭代的列表增长代码会给出 IndexError: list assignment index out of range?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:29