Why does this iterative list-growing code give IndexError: list assignment index out of range?(为什么这个迭代的列表增长代码会给出 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么这个迭代的列表增长代码会给出 IndexErro
				
        
 
            
        基础教程推荐
- 包装空间模型 2022-01-01
 - PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
 - 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
 - Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
 - 在Python中从Azure BLOB存储中读取文件 2022-01-01
 - PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
 - 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
 - 求两个直方图的卷积 2022-01-01
 - 修改列表中的数据帧不起作用 2022-01-01
 - 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				