You cannot assign to a list like lst[i] = something
, unless the list already is initialized with at least i+1
elements.
(除非已使用至少i+1
元素初始化列表,否则不能分配像lst[i] = something
的列表。)
You need to use append to add elements to the end of the list. (您需要使用append将元素添加到列表的末尾。)
lst.append(something)
. (lst.append(something)
。)
(You could use the assignment notation if you were using a dictionary).
((如果使用字典,可以使用赋值表示法)。)
Creating an empty list:
(创建一个空列表:)
>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]
Assigning a value to an existing element of the above list:
(将值分配给上面列表的现有元素:)
>>> l[1] = 5
>>> l
[None, 5, None, None, None, None, None, None, None, None]
Keep in mind that something like l[15] = 5
would still fail, as our list has only 10 elements.
(请记住,像l[15] = 5
这样的东西仍然会失败,因为我们的列表只有10个元素。)
range(x) creates a list from [0, 1, 2, ... x-1]
(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]
Using a function to create a list:
(使用函数创建列表:)
>>> 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]
List comprehension (Using the squares because for range you don't need to do all this, you can just return 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]