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]]
>>>
如您所见,每个元素都指向同一列表对象。为了解决这个问题,可以创建一个方法,将每个位置初始化为不同的对象引用。
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方式(而不是编写函数),但我不确定它是什么。很高兴得到更正!
编辑:范围(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]]