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]]
添加回答
舉報