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方式(而不是编写函数)来执行此操作,但是我不确定它是什么。很高兴得到纠正!
编辑:这是 [ [] 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]]