为什么这个迭代列表增长代码给出 IndexError: list assignment index out of range? [英] Why does this iterative list-growing code give IndexError: list assignment index out of range?

查看:15
本文介绍了为什么这个迭代列表增长代码给出 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆