如何在Python中定义一个二维数组

时间:2021-10-06 22:44:23

I want to define a two-dimensional array without an initialized length like this:

我想定义一个二维数组,没有像这样初始化长度:

Matrix = [][]

but it does not work...

但它不起作用……

I've tried the code below, but it is wrong too:

我试过下面的代码,但是也错了:

Matrix = [5][5]

Error:

错误:

Traceback ...IndexError: list index out of range

What is my mistake?

我的错误是什么?

21 个解决方案

#1


717  

You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this"list comprehension".

你在技术上试图索引一个未初始化的数组。在添加项目之前,必须先用列表初始化外部列表;Python调用这个“列表理解”。

# Creates a list containing 5 lists, each of 8 items, all set to 0w, h = 8, 5;Matrix = [[0 for x in range(w)] for y in range(h)] 

You can now add items to the list:

Matrix[0][0] = 1Matrix[6][0] = 3 # error! range... Matrix[0][6] = 3 # validprint Matrix[0][0] # prints 1x, y = 0, 6 print Matrix[x][y] # prints 3; be careful with indexing! 

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.

虽然您可以按自己的意愿来命名它们,但是我这样看是为了避免由于索引而引起的混乱,如果您对内部和外部列表都使用“x”,并且希望使用一个非方阵的话。

#2


311  

If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:

如果你真的想要一个矩阵,你最好使用numpy。numpy中的矩阵操作通常使用二维数组类型。创建新数组的方法有很多;其中最有用的是0函数,它接受形状参数并返回给定形状的数组,其值初始化为0:

>>> import numpy>>> numpy.zeros((5, 5))array([[ 0.,  0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.,  0.]])

numpy provides a matrix type as well. It's less commonly used, and some people recommend against using it. But it's useful for people coming to numpy from Matlab, and in some other contexts. I thought I'd include it since we're talking about matrices!

numpy还提供了一个矩阵类型。它不太常用,一些人建议不要使用它。但是对于从Matlab中学习numpy的人,以及在其他环境中,它是很有用的。我想我应该把它包括进来因为我们讨论的是矩阵!

>>> numpy.matrix([[1, 2], [3, 4]])matrix([[1, 2],        [3, 4]])

Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):

以下是创建二维数组和矩阵的一些其他方法(为了紧凑性,输出被删除):

numpy.matrix('1 2; 3 4')                 # use Matlab-style syntaxnumpy.arange(25).reshape((5, 5))         # create a 1-d range and reshapenumpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshapenumpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshapenumpy.empty((5, 5))                      # allocate, but don't initializenumpy.ones((5, 5))                       # initialize with onesnumpy.ndarray((5, 5))                    # use the low-level constructor

#3


245  

Here is a shorter notation for initializing a list of lists:

下面是一个简短的列表初始化表示法:

matrix = [[0]*5 for i in range(5)]

Unfortunately shortening this to something like 5*[5*[0]] doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example:

不幸的是,将它缩短为5*[5*[0]]并不能真正起作用,因为你最终会得到相同列表的5个副本,所以当你修改其中一个时,它们都会发生变化,例如:

>>> matrix = 5*[5*[0]]>>> matrix[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]>>> matrix[4][4] = 2>>> matrix[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]

#4


72  

If you want to create an empty matrix, the correct syntax is

如果您想创建一个空矩阵,正确的语法是

matrix = [[]]

And if you want to generate a matrix of size 5 filled with 0,

如果你想生成一个5大小为0的矩阵,

matrix = [[0 for i in xrange(5)] for i in xrange(5)]

#5


63  

If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead:

如果您想要的只是一个二维容器来保存一些元素,那么您可以方便地使用字典来代替:

Matrix = {}

Then you can do:

然后你可以做:

Matrix[1,2] = 15print Matrix[1,2]

This works because 1,2 is a tuple, and you're using it as a key to index the dictionary. The result is similar to a dumb sparse matrix.

这是因为1 2是一个元组,您将它用作索引字典的键。结果与哑矩阵相似。

As indicated by osa and Josap Valls, you can also use Matrix = collections.defaultdict(lambda:0) so that the missing elements have a default value of 0.

正如osa和Josap Valls指出的,您还可以使用Matrix = collection .defaultdict(lambda:0),以便丢失的元素具有0的默认值。

Vatsal further points that this method is probably not very efficient for large matrices and should only be used in non performance-critical parts of the code.

Vatsal进一步指出,这种方法对于大型矩阵可能不是很有效,应该只用于代码的非性能关键部分。

#6


34  

In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:

在Python中,您将创建一个列表列表。您不必提前声明维度,但是您可以这样做。例如:

matrix = []matrix.append([])matrix.append([])matrix[0].append(2)matrix[1].append(3)

Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a "two-dimensional list":

现在,矩阵[0][0]= 2,矩阵[1][0]= 3。您还可以使用列表理解语法。本例使用它两次构建一个“二维列表”:

from itertools import count, takewhilematrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]

#7


16  

The accepted answer is good and correct, but it took me a while to understand that I could also use it to create a completely empty array.

公认的答案是正确的,但是我花了一段时间才理解我也可以使用它来创建一个完全空的数组。

l =  [[] for _ in range(3)]

results in

结果

[[], [], []]

#8


13  

You should make a list of lists, and the best way is to use nested comprehensions:

你应该列出一个列表,最好的方法是使用嵌套的理解:

>>> matrix = [[0 for i in range(5)] for j in range(5)]>>> pprint.pprint(matrix)[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

On your [5][5] example, you are creating a list with an integer "5" inside, and try to access its 5th item, and that naturally raises an IndexError because there is no 5th item:

在[5][5]示例中,您正在创建一个包含整数“5”的列表,并尝试访问它的第5项,这自然会引发一个IndexError,因为没有第5项:

>>> l = [5]>>> l[5]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: list index out of range

#9


9  

To declare a matrix of zeros (ones):

声明一个0(1)的矩阵:

numpy.zeros((x, y))

e.g.

如。

>>> numpy.zeros((3, 5))    array([[ 0.,  0.,  0.,  0.,  0.],   [ 0.,  0.,  0.,  0.,  0.],   [ 0.,  0.,  0.,  0.,  0.]])

or numpy.ones((x, y))e.g.

或numpy。((x,y))。

>>> np.ones((3, 5))array([[ 1.,  1.,  1.,  1.,  1.],   [ 1.,  1.,  1.,  1.,  1.],   [ 1.,  1.,  1.,  1.,  1.]])

Even three dimensions are possible.(http://www.astro.ufl.edu/~warner/prog/python.html see --> Multi-dimensional arrays)

甚至三维都是可能的。

#10


8  

A rewrite for easy reading:

为了便于阅读,重写:

# 2D array/ matrix# 5 rows, 5 colsrows_count = 5cols_count = 5# create#     creation looks reverse#     create an array of "cols_count" cols, for each of the "rows_count" rows#        all elements are initialized to 0two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]# index is from 0 to 4#     for both rows & cols#     since 5 rows, 5 cols# usetwo_d_array[0][0] = 1print two_d_array[0][0]  # prints 1   # 1st row, 1st col (top-left element of matrix)two_d_array[1][0] = 2print two_d_array[1][0]  # prints 2   # 2nd row, 1st coltwo_d_array[1][4] = 3print two_d_array[1][4]  # prints 3   # 2nd row, last coltwo_d_array[4][4] = 4print two_d_array[4][4]  # prints 4   # last row, last col (right, bottom element of matrix)

#11


8  

I'm on my first Python script, and I was a little confused by the square matrix example so I hope the below example will help you save some time:

我使用的是我的第一个Python脚本,我对方阵示例有点迷惑,所以我希望下面的示例能帮助您节省一些时间:

 # Creates a 2 x 5 matrix Matrix = [[0 for y in xrange(5)] for x in xrange(2)]

so that

Matrix[1][4] = 2 # ValidMatrix[4][1] = 3 # IndexError: list index out of range

#12


7  

I read in comma separated files like this:

我用逗号分隔的文件读:

data=[]for l in infile:    l = split(',')    data.append(l)

The list "data" is then a list of lists with index data[row][col]

然后列表“数据”就是带有索引数据的列表[row][col]

#13


7  

Use:

使用:

matrix = [[0]*5 for i in range(5)]

The *5 for the first dimension works because at this level the data is immutable.

第一个维度的*5起作用,因为在这个层次上数据是不可变的。

#14


7  

Using NumPy you can initialize empty matrix like this:

使用NumPy可以初始化空矩阵如下:

import numpy as npmm = np.matrix([])

And later append data like this:

之后添加如下数据:

mm = np.append(mm, [[1,2]], axis=1)

#15


4  

# Creates a list containing 5 lists initialized to 0Matrix = [[0]*5]*5

Be careful about this short expression, see full explanation down in @F.J's answer

注意这个简短的表达,请参阅@F的完整解释。我的回答

#16


4  

Use:

使用:

import copydef ndlist(*args, init=0):    dp = init    for x in reversed(args):        dp = [copy.deepcopy(dp) for _ in range(x)]    return dpl = ndlist(1,2,3,4) # 4 dimensional list initialized with 0'sl[0][1][2][3] = 1

I do think NumPy is the way to go. The above is a generic one if you don't want to use NumPy.

我认为麻木是正确的。如果您不想使用NumPy,上面的是通用的。

#17


3  

That's what dictionary is made for!

matrix = {}

You can define keys and values in two ways:

你可以用两种方式定义键和值:

matrix[0,0] = value

or

matrix = { (0,0)  : value }

Result:

结果:

   [ value,  value,  value,  value,  value],   [ value,  value,  value,  value,  value],   ...

#18


3  

If you want to be able to think it as a 2D array rather than being forced to think in term of a list of lists (much more natural in my opinion), you can do the following:

如果你想把它想象成一个二维数组,而不是*去考虑列表(在我看来更自然),你可以做以下事情:

import numpyNx=3; Ny=4my2Dlist= numpy.zeros((Nx,Ny)).tolist()

The result is a list (not a NumPy array), and you can overwrite the individual positions with numbers, strings, whatever.

结果是一个列表(不是NumPy数组),您可以用数字、字符串之类的方式覆盖各个位置。

#19


2  

If you don't have size information before start then create two one-dimensional lists.

如果在开始之前没有大小信息,那么创建两个一维列表。

list 1: To store rowslist 2: Actual two-dimensional matrix

清单1:存储rowslist 2:实际的二维矩阵

Store the entire row in the 1st list. Once done, append list 1 into list 2:

将整个行存储在第一个列表中。完成后,将列表1添加到列表2:

from random import randintcoordinates=[]temp=[]points=int(raw_input("Enter No Of Coordinates >"))for i in range(0,points):    randomx=randint(0,1000)    randomy=randint(0,1000)    temp=[]    temp.append(randomx)    temp.append(randomy)    coordinates.append(temp)print coordinates

Output:

输出:

Enter No Of Coordinates >4[[522, 96], [378, 276], [349, 741], [238, 439]]

#20


2  

by using list :

通过使用清单:

matrix_in_python  = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]

by using dict:you can also store this info in the hash table for fast searching like

通过使用dict:您还可以将该信息存储在哈希表中,以便进行快速搜索

matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};

matrix['1'] will give you result in O(1) time

矩阵['1']会给你O(1)时间的结果

*nb: you need to deal with a collision in the hash table

*nb:您需要处理哈希表中的冲突

#21


0  

This is how I usually create 2D arrays in python.

这就是我通常在python中创建2D数组的方式。

col = 3row = 4array = [[0] * col for _ in range(row)]

I find this syntax easy to remember compared to using to for loops in a list comprehension.

与在列表理解中使用to for循环相比,我发现这个语法很容易记住。

#1


717  

You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this"list comprehension".

你在技术上试图索引一个未初始化的数组。在添加项目之前,必须先用列表初始化外部列表;Python调用这个“列表理解”。

# Creates a list containing 5 lists, each of 8 items, all set to 0w, h = 8, 5;Matrix = [[0 for x in range(w)] for y in range(h)] 

You can now add items to the list:

Matrix[0][0] = 1Matrix[6][0] = 3 # error! range... Matrix[0][6] = 3 # validprint Matrix[0][0] # prints 1x, y = 0, 6 print Matrix[x][y] # prints 3; be careful with indexing! 

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.

虽然您可以按自己的意愿来命名它们,但是我这样看是为了避免由于索引而引起的混乱,如果您对内部和外部列表都使用“x”,并且希望使用一个非方阵的话。

#2


311  

If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:

如果你真的想要一个矩阵,你最好使用numpy。numpy中的矩阵操作通常使用二维数组类型。创建新数组的方法有很多;其中最有用的是0函数,它接受形状参数并返回给定形状的数组,其值初始化为0:

>>> import numpy>>> numpy.zeros((5, 5))array([[ 0.,  0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.,  0.]])

numpy provides a matrix type as well. It's less commonly used, and some people recommend against using it. But it's useful for people coming to numpy from Matlab, and in some other contexts. I thought I'd include it since we're talking about matrices!

numpy还提供了一个矩阵类型。它不太常用,一些人建议不要使用它。但是对于从Matlab中学习numpy的人,以及在其他环境中,它是很有用的。我想我应该把它包括进来因为我们讨论的是矩阵!

>>> numpy.matrix([[1, 2], [3, 4]])matrix([[1, 2],        [3, 4]])

Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):

以下是创建二维数组和矩阵的一些其他方法(为了紧凑性,输出被删除):

numpy.matrix('1 2; 3 4')                 # use Matlab-style syntaxnumpy.arange(25).reshape((5, 5))         # create a 1-d range and reshapenumpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshapenumpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshapenumpy.empty((5, 5))                      # allocate, but don't initializenumpy.ones((5, 5))                       # initialize with onesnumpy.ndarray((5, 5))                    # use the low-level constructor

#3


245  

Here is a shorter notation for initializing a list of lists:

下面是一个简短的列表初始化表示法:

matrix = [[0]*5 for i in range(5)]

Unfortunately shortening this to something like 5*[5*[0]] doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example:

不幸的是,将它缩短为5*[5*[0]]并不能真正起作用,因为你最终会得到相同列表的5个副本,所以当你修改其中一个时,它们都会发生变化,例如:

>>> matrix = 5*[5*[0]]>>> matrix[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]>>> matrix[4][4] = 2>>> matrix[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]

#4


72  

If you want to create an empty matrix, the correct syntax is

如果您想创建一个空矩阵,正确的语法是

matrix = [[]]

And if you want to generate a matrix of size 5 filled with 0,

如果你想生成一个5大小为0的矩阵,

matrix = [[0 for i in xrange(5)] for i in xrange(5)]

#5


63  

If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead:

如果您想要的只是一个二维容器来保存一些元素,那么您可以方便地使用字典来代替:

Matrix = {}

Then you can do:

然后你可以做:

Matrix[1,2] = 15print Matrix[1,2]

This works because 1,2 is a tuple, and you're using it as a key to index the dictionary. The result is similar to a dumb sparse matrix.

这是因为1 2是一个元组,您将它用作索引字典的键。结果与哑矩阵相似。

As indicated by osa and Josap Valls, you can also use Matrix = collections.defaultdict(lambda:0) so that the missing elements have a default value of 0.

正如osa和Josap Valls指出的,您还可以使用Matrix = collection .defaultdict(lambda:0),以便丢失的元素具有0的默认值。

Vatsal further points that this method is probably not very efficient for large matrices and should only be used in non performance-critical parts of the code.

Vatsal进一步指出,这种方法对于大型矩阵可能不是很有效,应该只用于代码的非性能关键部分。

#6


34  

In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:

在Python中,您将创建一个列表列表。您不必提前声明维度,但是您可以这样做。例如:

matrix = []matrix.append([])matrix.append([])matrix[0].append(2)matrix[1].append(3)

Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a "two-dimensional list":

现在,矩阵[0][0]= 2,矩阵[1][0]= 3。您还可以使用列表理解语法。本例使用它两次构建一个“二维列表”:

from itertools import count, takewhilematrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]

#7


16  

The accepted answer is good and correct, but it took me a while to understand that I could also use it to create a completely empty array.

公认的答案是正确的,但是我花了一段时间才理解我也可以使用它来创建一个完全空的数组。

l =  [[] for _ in range(3)]

results in

结果

[[], [], []]

#8


13  

You should make a list of lists, and the best way is to use nested comprehensions:

你应该列出一个列表,最好的方法是使用嵌套的理解:

>>> matrix = [[0 for i in range(5)] for j in range(5)]>>> pprint.pprint(matrix)[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

On your [5][5] example, you are creating a list with an integer "5" inside, and try to access its 5th item, and that naturally raises an IndexError because there is no 5th item:

在[5][5]示例中,您正在创建一个包含整数“5”的列表,并尝试访问它的第5项,这自然会引发一个IndexError,因为没有第5项:

>>> l = [5]>>> l[5]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: list index out of range

#9


9  

To declare a matrix of zeros (ones):

声明一个0(1)的矩阵:

numpy.zeros((x, y))

e.g.

如。

>>> numpy.zeros((3, 5))    array([[ 0.,  0.,  0.,  0.,  0.],   [ 0.,  0.,  0.,  0.,  0.],   [ 0.,  0.,  0.,  0.,  0.]])

or numpy.ones((x, y))e.g.

或numpy。((x,y))。

>>> np.ones((3, 5))array([[ 1.,  1.,  1.,  1.,  1.],   [ 1.,  1.,  1.,  1.,  1.],   [ 1.,  1.,  1.,  1.,  1.]])

Even three dimensions are possible.(http://www.astro.ufl.edu/~warner/prog/python.html see --> Multi-dimensional arrays)

甚至三维都是可能的。

#10


8  

A rewrite for easy reading:

为了便于阅读,重写:

# 2D array/ matrix# 5 rows, 5 colsrows_count = 5cols_count = 5# create#     creation looks reverse#     create an array of "cols_count" cols, for each of the "rows_count" rows#        all elements are initialized to 0two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]# index is from 0 to 4#     for both rows & cols#     since 5 rows, 5 cols# usetwo_d_array[0][0] = 1print two_d_array[0][0]  # prints 1   # 1st row, 1st col (top-left element of matrix)two_d_array[1][0] = 2print two_d_array[1][0]  # prints 2   # 2nd row, 1st coltwo_d_array[1][4] = 3print two_d_array[1][4]  # prints 3   # 2nd row, last coltwo_d_array[4][4] = 4print two_d_array[4][4]  # prints 4   # last row, last col (right, bottom element of matrix)

#11


8  

I'm on my first Python script, and I was a little confused by the square matrix example so I hope the below example will help you save some time:

我使用的是我的第一个Python脚本,我对方阵示例有点迷惑,所以我希望下面的示例能帮助您节省一些时间:

 # Creates a 2 x 5 matrix Matrix = [[0 for y in xrange(5)] for x in xrange(2)]

so that

Matrix[1][4] = 2 # ValidMatrix[4][1] = 3 # IndexError: list index out of range

#12


7  

I read in comma separated files like this:

我用逗号分隔的文件读:

data=[]for l in infile:    l = split(',')    data.append(l)

The list "data" is then a list of lists with index data[row][col]

然后列表“数据”就是带有索引数据的列表[row][col]

#13


7  

Use:

使用:

matrix = [[0]*5 for i in range(5)]

The *5 for the first dimension works because at this level the data is immutable.

第一个维度的*5起作用,因为在这个层次上数据是不可变的。

#14


7  

Using NumPy you can initialize empty matrix like this:

使用NumPy可以初始化空矩阵如下:

import numpy as npmm = np.matrix([])

And later append data like this:

之后添加如下数据:

mm = np.append(mm, [[1,2]], axis=1)

#15


4  

# Creates a list containing 5 lists initialized to 0Matrix = [[0]*5]*5

Be careful about this short expression, see full explanation down in @F.J's answer

注意这个简短的表达,请参阅@F的完整解释。我的回答

#16


4  

Use:

使用:

import copydef ndlist(*args, init=0):    dp = init    for x in reversed(args):        dp = [copy.deepcopy(dp) for _ in range(x)]    return dpl = ndlist(1,2,3,4) # 4 dimensional list initialized with 0'sl[0][1][2][3] = 1

I do think NumPy is the way to go. The above is a generic one if you don't want to use NumPy.

我认为麻木是正确的。如果您不想使用NumPy,上面的是通用的。

#17


3  

That's what dictionary is made for!

matrix = {}

You can define keys and values in two ways:

你可以用两种方式定义键和值:

matrix[0,0] = value

or

matrix = { (0,0)  : value }

Result:

结果:

   [ value,  value,  value,  value,  value],   [ value,  value,  value,  value,  value],   ...

#18


3  

If you want to be able to think it as a 2D array rather than being forced to think in term of a list of lists (much more natural in my opinion), you can do the following:

如果你想把它想象成一个二维数组,而不是*去考虑列表(在我看来更自然),你可以做以下事情:

import numpyNx=3; Ny=4my2Dlist= numpy.zeros((Nx,Ny)).tolist()

The result is a list (not a NumPy array), and you can overwrite the individual positions with numbers, strings, whatever.

结果是一个列表(不是NumPy数组),您可以用数字、字符串之类的方式覆盖各个位置。

#19


2  

If you don't have size information before start then create two one-dimensional lists.

如果在开始之前没有大小信息,那么创建两个一维列表。

list 1: To store rowslist 2: Actual two-dimensional matrix

清单1:存储rowslist 2:实际的二维矩阵

Store the entire row in the 1st list. Once done, append list 1 into list 2:

将整个行存储在第一个列表中。完成后,将列表1添加到列表2:

from random import randintcoordinates=[]temp=[]points=int(raw_input("Enter No Of Coordinates >"))for i in range(0,points):    randomx=randint(0,1000)    randomy=randint(0,1000)    temp=[]    temp.append(randomx)    temp.append(randomy)    coordinates.append(temp)print coordinates

Output:

输出:

Enter No Of Coordinates >4[[522, 96], [378, 276], [349, 741], [238, 439]]

#20


2  

by using list :

通过使用清单:

matrix_in_python  = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]

by using dict:you can also store this info in the hash table for fast searching like

通过使用dict:您还可以将该信息存储在哈希表中,以便进行快速搜索

matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};

matrix['1'] will give you result in O(1) time

矩阵['1']会给你O(1)时间的结果

*nb: you need to deal with a collision in the hash table

*nb:您需要处理哈希表中的冲突

#21


0  

This is how I usually create 2D arrays in python.

这就是我通常在python中创建2D数组的方式。

col = 3row = 4array = [[0] * col for _ in range(row)]

I find this syntax easy to remember compared to using to for loops in a list comprehension.

与在列表理解中使用to for循环相比,我发现这个语法很容易记住。