您不能分配给这样的列表xs[i] = value
,除非列表已至少初始化i+1
元素(因为第一个索引是 0)。相反,使用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 个元素。
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)
):
>>> def display():
... return [x**2 for x in range(9)]
...
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]