小编典典
你不能分配给类似的列表lst[i] = something,除非该列表已至少已使用i+1元素初始化。你需要使用append将元素添加到列表的末尾。lst.append(something)。
(如果使用字典,则可以使用分配符号)。
创建一个空列表:
>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]
为上述列表的现有元素分配一个值:
>>> l[1] = 5
>>> l
[None, 5, None, None, None, None, None, None, None, None]
请记住,类似的操作l[15] = 5仍然会失败,因为我们的列表只有10个元素。
range(x)从[0,1,2,... x-1]创建一个列表
# 2.X only. Use list(range(10)) in 3.X.
>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
使用函数创建列表:
>>> def display():
... s1 = []
... for i in range(9): # This is just to tell you how to create a list.
... s1.append(i)
... return s1
...
>>> 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]
2020-02-19