如何创建一个可容纳 10 个元素的空列表?
之后,我想在该列表中分配值。例如:
xs = list() for i in range(0, 9): xs[i] = i
但是,结果却是IndexError: list assignment index out of range。为什么呢?
IndexError: list assignment index out of range
您不能对像 这样的列表进行赋值xs[i] = value,除非该列表已经初始化为至少i+1元素(因为第一个索引为 0)。相反,使用xs.append(value)将元素添加到列表末尾。(虽然如果您使用的是字典而不是列表,则可以使用赋值符号。)
xs[i] = value
i+1
xs.append(value)
创建一个空列表:
>>> xs = [None] * 10 >>> xs [None, None, None, None, None, None, None, None, None, None]
为上述列表的现有元素分配一个值:
>>> xs[1] = 5 >>> xs [None, 5, None, None, None, None, None, None, None, None]
请记住,类似的操作xs[15] = 5仍然会失败,因为我们的列表只有 10 个元素。
xs[15] = 5
range(x) 从 [0, 1, 2, … x-1] 创建一个列表
# 2.X only. Use list(range(10)) in 3.X. >>> xs = range(10) >>> xs [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
使用函数创建列表:
>>> def display(): ... xs = [] ... for i in range(9): # This is just to tell you how to create a list. ... xs.append(i) ... return xs ... >>> print display() [0, 1, 2, 3, 4, 5, 6, 7, 8]
列表理解(使用正方形,因为对于范围你不需要做所有这些,你只需返回range(0,9)):
range(0,9)
>>> def display(): ... return [x**2 for x in range(9)] ... >>> print display() [0, 1, 4, 9, 16, 25, 36, 49, 64]