3 回答
TA贡献1829条经验 获得超9个赞
您不能将以下列表分配给lst[i] = something,除非列表已被至少初始化为i+1元素。您需要使用追加将元素添加到列表的末尾。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]
TA贡献1799条经验 获得超8个赞
>>> l = [None] * 10 >>> l [None, None, None, None, None, None, None, None, None, None]
>>> a = [[]]*10>>> a[[], [], [], [], [], [], [], [], [], []]>>> a[0].append(0)>>> a[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]>>>
def init_list_of_objects(size): list_of_objects = list() for i in range(0,size): list_of_objects.append( list() ) #different object reference each time return list_of_objects>>> a = init_list_of_objects(10)>>> a[[], [], [], [], [], [], [], [], [], []]>>> a[0].append(0)>>> a[[0], [], [], [], [], [], [], [], [], []]>>>
[ [] for _ in range(10)]
>>> [ [random.random() for _ in range(2) ] for _ in range(5)]>>> [[0.7528051908943816, 0.4325669600055032], [0.510983236521753, 0.7789949902294716], [0.09475179523690558, 0.30216475640534635], [0.3996890132468158, 0.6374322093017013], [0.3374204010027543, 0.4514925173253973]]
添加回答
举报