PIPIONE
您不能将以下列表分配给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]
守着星空守着你
varunl目前接受的答案 >>> l = [None] * 10
>>> l [None, None, None, None, None, None, None, None, None, None]对于像数字这样的非引用类型,效果很好。不幸的是,如果您想要创建一个列表,您将遇到引用错误。Python 2.7.6中的示例:>>> a = [[]]*10>>> a[[], [], [], [], [], [], [], [], [], []]>>> a[0].append(0)>>> a[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]>>>如您所见,每个元素都指向同一个List对象。为了解决这个问题,您可以创建一个将每个位置初始化为不同对象引用的方法。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], [], [], [], [], [], [], [], [], []]>>>可能有一种默认的内置python方式(而不是编写函数),但我不确定它是什么。会很高兴被纠正的!编辑:它是[ [] 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]]