如何在Python中初始化一个二维数组?

我开始python,我试图使用一个二维列表,我最初填补了每个地方相同的variables。 我想出了这个:

def initialize_twodlist(foo): twod_list = [] new = [] for i in range (0, 10): for j in range (0, 10): new.append(foo) twod_list.append(new) new = [] 

它给出了预期的结果,但感觉像一个解决方法。 有一个更容易/更短/更优雅的方式来做到这一点?

Python中经常出现的模式是

 bar = [] for item in some_iterable: bar.append(SOME EXPRESSION) 

这有助于激发引入列表parsing,将该片段转换为

 bar = [SOME EXPRESSION for item in some_iterable] 

这是更短,有时更清晰。 通常你会养成认识这些习惯的习惯,并经常用理解来代替循环。

你的代码遵循这个模式两次

 twod_list = [] \ for i in range (0, 10): \ new = [] \ can be replaced } this too for j in range (0, 10): } with a list / new.append(foo) / comprehension / twod_list.append(new) / 

你可以使用列表理解 :

 x = [[foo for i in range(10)] for j in range(10)] # x is now a 10x10 array of 'foo' (which can depend on i and j if you want) 

这种方式比嵌套的列表parsing更快

 [x[:] for x in [[foo] * 10] * 10] # for immutable foo! 

这里是一些python3的时间,小型和大型列表

 $python3 -m timeit '[x[:] for x in [[1] * 10] * 10]' 1000000 loops, best of 3: 1.55 usec per loop $ python3 -m timeit '[[1 for i in range(10)] for j in range(10)]' 100000 loops, best of 3: 6.44 usec per loop $ python3 -m timeit '[x[:] for x in [[1] * 1000] * 1000]' 100 loops, best of 3: 5.5 msec per loop $ python3 -m timeit '[[1 for i in range(1000)] for j in range(1000)]' 10 loops, best of 3: 27 msec per loop 

说明:

[[foo]*10]*10创build一个重复10次的相同对象的列表。 你不能只用这个,因为修改一个元素会修改每一行中相同的元素!

x[:]等价于list(X)但效率更高一些,因为它避免了名称查找。 无论哪种方式,它创build每行的浅拷贝,所以现在所有的元素是独立的。

所有元素都是相同的foo对象,所以如果foo是可变的 ,你不能使用这个scheme,你必须使用

 import copy [[copy.deepcopy(foo) for x in range(10)] for y in range(10)] 

或者假设返回foo的类(或函数) Foo

 [[Foo() for x in range(10)] for y in range(10)] 

在Python中初始化一个二维数组:

 a = [[0 for x in range(columns)] for y in range(rows)] 
 [[foo for x in xrange(10)] for y in xrange(10)] 

通常当你想要multidimensional array时,你不需要一个列表的列表,而是一个numpy数组或可能是一个字典。

例如,你可以用numpy做类似的事情

 import numpy a = numpy.empty((10, 10)) a.fill(foo) 

你可以做到这一点:

 [[element] * numcols] * numrows 

例如:

 >>> [['a'] *3] * 2 [['a', 'a', 'a'], ['a', 'a', 'a']] 

但是这有一个不希望的副作用:

 >>> b = [['a']*3]*3 >>> b [['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']] >>> b[1][1] 'a' >>> b[1][1] = 'b' >>> b [['a', 'b', 'a'], ['a', 'b', 'a'], ['a', 'b', 'a']] 

不要使用[[v] * n] * n,这是一个陷阱!

 >>> a = [[0]*3]*3 >>> a [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> a[0][0]=1 >>> a [[1, 0, 0], [1, 0, 0], [1, 0, 0]] 

如果它是一个稀疏的数组,你可能会更好的使用一个带有元组的字典:

 dict = {} key = (a,b) dict[key] = value ... 

用最简单的想法来创造这个。

 wtod_list = [] 

并添加大小:

 wtod_list = [[0 for x in xrange(10))] for x in xrange(10)] 

或者如果我们想要首先宣布大小。 我们只使用:

  wtod_list = [[0 for x in xrange(10))] for x in xrange(10)] 

正如@Arnab和@Mike所指出的,一个数组不是一个列表。 几乎不同的是1)在初始化过程中数组的大小是固定的2)数组通常支持比列表更小的操作。

在大多数情况下可能是矫枉过正,但这里是一个基本的二维数组实现,利用硬件数组实现使用python ctypes(C库)

 import ctypes class Array: def __init__(self,size,foo): #foo is the initial value self._size = size ArrayType = ctypes.py_object * size self._array = ArrayType() for i in range(size): self._array[i] = foo def __getitem__(self,index): return self._array[index] def __setitem__(self,index,value): self._array[index] = value def __len__(self): return self._size class TwoDArray: def __init__(self,columns,rows,foo): self._2dArray = Array(rows,foo) for i in range(rows): self._2dArray[i] = Array(columns,foo) def numRows(self): return len(self._2dArray) def numCols(self): return len((self._2dArray)[0]) def __getitem__(self,indexTuple): row = indexTuple[0] col = indexTuple[1] assert row >= 0 and row < self.numRows() \ and col >=0 and col < self.numCols(),\ "Array script out of range" return ((self._2dArray)[row])[col] if(__name__ == "__main__"): twodArray = TwoDArray(4,5,5)#sample input print(twodArray[2,3]) 

这是我find的最好的教程新的程序员,并没有使用额外的库。 我想要更好的东西。

 def initialize_twodlist(value): list=[] for row in range(10): list.append([value]*10) return list 

这是一个更简单的方法:

 import numpy as np twoD = np.array([[]*m]*n) 

要初始化所有具有任何“x”值的单元格,请使用:

 twoD = np.array([[x]*m]*n 
 Matrix={} for i in range(0,3): for j in range(0,3): Matrix[i,j] = raw_input("Enter the matrix:") 
 from random import randint l = [] for i in range(10): k=[] for j in range(10): a= randint(1,100) k.append(a) l.append(k) print(l) print(max(l[2])) b = [] for i in range(10): a = l[i][5] b.append(a) print(min(b))