如何在Python中定义二维数组

问题:如何在Python中定义二维数组

我想定义一个没有初始化长度的二维数组,如下所示:

Matrix = [][]

但这不起作用…

我已经尝试过下面的代码,但是它也是错误的:

Matrix = [5][5]

错误:

Traceback ...

IndexError: list index out of range

我怎么了

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?


回答 0

从技术上讲,您正在尝试索引未初始化的数组。您必须先使用列表初始化外部列表,然后再添加项目。Python将其称为“列表理解”。

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

您现在可以将项目添加到列表中:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range... 
Matrix[0][6] = 3 # valid

请注意,矩阵是“ y”地址主地址,换句话说,“ y索引”位于“ x索引”之前。

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

尽管您可以根据需要命名它们,但是如果您对内部列表和外部列表都使用“ x”,并且希望使用非平方矩阵,那么我会以这种方式来避免索引可能引起的混淆。

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”.

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, 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] = 1
Matrix[6][0] = 3 # error! range... 
Matrix[0][6] = 3 # valid

Note that the matrix is “y” address major, in other words, the “y index” comes before the “x index”.

print Matrix[0][0] # prints 1
x, 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.


回答 1

如果您确实需要矩阵,最好使用numpy。在numpy大多数情况下,矩阵运算使用具有二维的数组类型。有很多方法可以创建一个新数组。最有用的zeros函数之一是函数,它采用shape参数并返回给定形状的数组,其值初始化为零:

>>> 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.arange(25).reshape((5, 5))         # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshape
numpy.empty((5, 5))                      # allocate, but don't initialize
numpy.ones((5, 5))                       # initialize with ones

numpy也提供了一种matrix类型,但是不再建议将其用于任何用途,以后可能会删除numpy它。

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:

>>> 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.]])

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

numpy.arange(25).reshape((5, 5))         # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshape
numpy.empty((5, 5))                      # allocate, but don't initialize
numpy.ones((5, 5))                       # initialize with ones

numpy provides a matrix type as well, but it is no longer recommended for any use, and may be removed from numpy in the future.


回答 2

这是用于初始化列表列表的简短表示法:

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

不幸的是,将其缩短为类似的方法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]]

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:

>>> 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]]

回答 3

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

matrix = [[]]

如果您要生成大小为5的矩阵,并用0填充,

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

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,

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

回答 4

如果只需要一个二维容器来容纳某些元素,则可以方便地使用字典:

Matrix = {}

然后,您可以执行以下操作:

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

这是有效的,因为它1,2是一个元组,并且您将其用作索引字典的键。结果类似于哑的稀疏矩阵。

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

Vatsal进一步指出,该方法对于大型矩阵可能不是很有效,并且仅应在代码的非关键性能部分中使用。

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] = 15
print 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.

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.

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.


回答 5

在Python中,您将创建一个列表列表。您不必提前声明尺寸,但是可以声明。例如:

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

现在,matrix [0] [0] == 2和matrix [1] [0] ==3。您还可以使用列表理解语法。此示例两次使用它来构建“二维列表”:

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

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:

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”:

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

回答 6

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

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

结果是

[[], [], []]

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

[[], [], []]

回答 7

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

>>> 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]]

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

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

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:

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

回答 8

rows = int(input())
cols = int(input())

matrix = []
for i in range(rows):
  row = []
  for j in range(cols):
    row.append(0)
  matrix.append(row)

print(matrix)

为什么这么长的代码,Python您也会问?

很久以前,当我不熟悉Python时,我看到了编写2D矩阵的单行答案,并告诉自己我不再打算在Python中再次使用2D矩阵。(这些行很吓人,它没有给我有关Python所做的任何信息。还要注意,我不知道这些速记法。)

无论如何,这是一个来自C,CPP和Java背景的初学者的代码

给Python爱好者和专家的说明:请不要因为我编写了详细的代码而投了反对票。

rows = int(input())
cols = int(input())

matrix = []
for i in range(rows):
  row = []
  for j in range(cols):
    row.append(0)
  matrix.append(row)

print(matrix)

Why such a long code, that too in Python you ask?

Long back when I was not comfortable with Python, I saw the single line answers for writing 2D matrix and told myself I am not going to use 2-D matrix in Python again. (Those single lines were pretty scary and It didn’t give me any information on what Python was doing. Also note that I am not aware of these shorthands.)

Anyways, here’s the code for a beginner whose coming from C, CPP and Java background

Note to Python Lovers and Experts: Please do not down vote just because I wrote a detailed code.


回答 9

重写以便于阅读:

# 2D array/ matrix

# 5 rows, 5 cols
rows_count = 5
cols_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 0
two_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

# use
two_d_array[0][0] = 1
print two_d_array[0][0]  # prints 1   # 1st row, 1st col (top-left element of matrix)

two_d_array[1][0] = 2
print two_d_array[1][0]  # prints 2   # 2nd row, 1st col

two_d_array[1][4] = 3
print two_d_array[1][4]  # prints 3   # 2nd row, last col

two_d_array[4][4] = 4
print two_d_array[4][4]  # prints 4   # last row, last col (right, bottom element of matrix)

A rewrite for easy reading:

# 2D array/ matrix

# 5 rows, 5 cols
rows_count = 5
cols_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 0
two_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

# use
two_d_array[0][0] = 1
print two_d_array[0][0]  # prints 1   # 1st row, 1st col (top-left element of matrix)

two_d_array[1][0] = 2
print two_d_array[1][0]  # prints 2   # 2nd row, 1st col

two_d_array[1][4] = 3
print two_d_array[1][4]  # prints 3   # 2nd row, last col

two_d_array[4][4] = 4
print two_d_array[4][4]  # prints 4   # last row, last col (right, bottom element of matrix)

回答 10

采用:

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

第一维的* 5起作用是因为在此级别上,数据是不可变的。

Use:

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

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


回答 11

声明零(一)矩阵:

numpy.zeros((x, y))

例如

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

或numpy.ones((x,y))例如

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

甚至三个尺寸都是可能的。(http://www.astro.ufl.edu/~warner/prog/python.html参见->多维数组)

To declare a matrix of zeros (ones):

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.

>>> 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)


回答 12

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

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

与在列表理解中使用两个for循环相比,我发现此语法易于记住。

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

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

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


回答 13

我正在使用我的第一个Python脚本,我对方矩阵示例有些困惑,因此希望以下示例可以帮助您节省一些时间:

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

以便

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

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:

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

so that

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

回答 14

使用NumPy,您可以像这样初始化空矩阵:

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

然后像这样追加数据:

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

Using NumPy you can initialize empty matrix like this:

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

And later append data like this:

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

回答 15

我读了这样的逗号分隔文件:

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

然后,列表“数据”是带有索引数据的列表的列表[行] [列]

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]


回答 16

如果您希望能够将其视为2D数组,而不是被迫以列表列表的方式思考(我认为这自然得多),则可以执行以下操作:

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

结果是一个列表(不是NumPy数组),您可以用数字,字符串或其他内容覆盖各个位置。

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 numpy
Nx=3; Ny=4
my2Dlist= 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.


回答 17

这就是字典的用途!

matrix = {}

您可以通过两种方式定义

matrix[0,0] = value

要么

matrix = { (0,0)  : value }

结果:

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

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

采用:

import copy

def ndlist(*args, init=0):
    dp = init
    for x in reversed(args):
        dp = [copy.deepcopy(dp) for _ in range(x)]
    return dp

l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1

我确实认为NumPy是要走的路。如果您不想使用NumPy,则以上是一种通用方法。

Use:

import copy

def ndlist(*args, init=0):
    dp = init
    for x in reversed(args):
        dp = [copy.deepcopy(dp) for _ in range(x)]
    return dp

l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[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.


回答 19

通过使用列表:

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

通过使用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’]将为您提供O(1)时间的结果

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

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

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

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


回答 20

如果在开始之前没有尺寸信息,请创建两个一维列表。

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

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

from random import randint

coordinates=[]
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

输出:

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

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

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

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

from random import randint

coordinates=[]
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]]

回答 21

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

请注意此简短表达,请参见@FJ答案中的完整解释

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

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


回答 22

l=[[0]*(L) for _ in range(W)]

将比:

l = [[0 for x in range(L)] for y in range(W)] 
l=[[0]*(L) for _ in range(W)]

Will be faster than:

l = [[0 for x in range(L)] for y in range(W)] 

回答 23

您可以通过将两个或多个方括号或第三个方括号([]用逗号分隔)嵌套在一起来创建一个空的二维列表,如下所示:

Matrix = [[], []]

现在假设您要在Matrix[0][0]其后附加1,然后键入:

Matrix[0].append(1)

现在,键入Matrix并按Enter。输出将是:

[[1], []]

You can create an empty two dimensional list by nesting two or more square bracing or third bracket ([], separated by comma) with a square bracing, just like below:

Matrix = [[], []]

Now suppose you want to append 1 to Matrix[0][0] then you type:

Matrix[0].append(1)

Now, type Matrix and hit Enter. The output will be:

[[1], []]

回答 24

尝试这个:

rows = int(input('Enter rows\n'))
my_list = []
for i in range(rows):
    my_list.append(list(map(int, input().split())))

Try this:

rows = int(input('Enter rows\n'))
my_list = []
for i in range(rows):
    my_list.append(list(map(int, input().split())))

回答 25

如果您需要带有预定义数字的矩阵,则可以使用以下代码:

def matrix(rows, cols, start=0):
    return [[c + start + r * cols for c in range(cols)] for r in range(rows)]


assert matrix(2, 3, 1) == [[1, 2, 3], [4, 5, 6]]

In case if you need a matrix with predefined numbers you can use the following code:

def matrix(rows, cols, start=0):
    return [[c + start + r * cols for c in range(cols)] for r in range(rows)]


assert matrix(2, 3, 1) == [[1, 2, 3], [4, 5, 6]]

回答 26

这是在python中创建矩阵的代码片段:

# get the input rows and cols
rows = int(input("rows : "))
cols = int(input("Cols : "))

# initialize the list
l=[[0]*cols for i in range(rows)]

# fill some random values in it
for i in range(0,rows):
    for j in range(0,cols):
        l[i][j] = i+j

# print the list
for i in range(0,rows):
    print()
    for j in range(0,cols):
        print(l[i][j],end=" ")

如果我错过了什么,请提出建议。

Here is the code snippet for creating a matrix in python:

# get the input rows and cols
rows = int(input("rows : "))
cols = int(input("Cols : "))

# initialize the list
l=[[0]*cols for i in range(rows)]

# fill some random values in it
for i in range(0,rows):
    for j in range(0,cols):
        l[i][j] = i+j

# print the list
for i in range(0,rows):
    print()
    for j in range(0,cols):
        print(l[i][j],end=" ")

Please suggest if I have missed something.