29 回答 29

This answer is useful

1156

您在技术上试图索引一个未初始化的数组。在添加项目之前,您必须先用列表初始化外部列表;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”并且想要一个非方形矩阵,我会以这种方式查看它以避免索引可能出现的一些混淆。

于 2011-07-12T15:59:36.860 回答

This answer is useful

450

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

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

于 2011-07-12T16:04:52.710 回答

This answer is useful

376

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

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

于 2011-07-12T16:17:19.787 回答

This answer is useful

129

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

matrix = [[]]

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

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

于 2011-07-12T16:00:49.667 回答

This answer is useful

86

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

Matrix = {}

然后你可以这样做:

Matrix[1,2] = 15

print Matrix[1,2]

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

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

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

于 2014-05-29T07:23:00.180 回答

This answer is useful

47

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

于 2011-07-12T16:04:15.927 回答

This answer is useful

28

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 中使用 2-D 矩阵。(那些单行非常可怕,它没有给我任何关于 Python 正在做什么的信息。另请注意,我不知道这些速记。)

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

Python爱好者和专家注意:请不要仅仅因为我写了详细的代码而投反对票。

于 2018-07-06T21:06:04.747 回答

This answer is useful

25

您应该制作一个列表列表,最好的方法是使用嵌套推导:

>>> 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”的列表,并尝试访问其第 5 项,这自然会引发 IndexError 因为没有第 5 项:

>>> l = [5]

>>> l[5]

Traceback (most recent call last):

File "", line 1, in

IndexError: list index out of range

于 2011-07-12T16:00:58.170 回答

This answer is useful

23

接受的答案是好的和正确的,但我花了一段时间才明白我也可以用它来创建一个完全空的数组。

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

结果是

[[], [], []]

于 2015-12-04T14:13:43.813 回答

This answer is useful

15

采用:

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

第一个维度的 *5 有效,因为在此级别数据是不可变的。

于 2015-08-05T01:10:07.243 回答

This answer is useful

15

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

col = 3

row = 4

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

与在列表推导中使用两个 for 循环相比,我发现这种语法更容易记住。

于 2018-06-03T15:32:51.113 回答

This answer is useful

13

为便于阅读而重写:

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

于 2016-07-02T11:33:54.490 回答

This answer is useful

12

声明一个零(一个)矩阵:

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见 --> 多维数组)

于 2013-12-07T20:45:17.830 回答

This answer is useful

11

我正在编写我的第一个 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

于 2014-03-28T10:14:25.273 回答

This answer is useful

10

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

import numpy as np

mm = np.matrix([])

然后像这样附加数据:

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

于 2017-09-15T10:54:31.720 回答

This answer is useful

10

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

Matrix = [[], []]

现在假设你想追加 1Matrix[0][0]然后你输入:

Matrix[0].append(1)

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

[[1], []]

如果您改为输入以下语句

Matrix[1].append(1)

那么矩阵将是

[[], [1]]

于 2019-08-03T09:42:31.677 回答

This answer is useful

8

这就是字典的用途!

matrix = {}

您可以通过两种方式定义键和值:

matrix[0,0] = value

或者

matrix = { (0,0) : value }

结果:

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

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

...

于 2017-01-16T06:38:58.807 回答

This answer is useful

7

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

data=[]

for l in infile:

l = split(',')

data.append(l)

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

于 2013-09-04T19:40:26.587 回答

This answer is useful

7

如果您希望能够将其视为 2D 数组,而不是被迫根据列表列表进行思考(在我看来更自然),您可以执行以下操作:

import numpy

Nx=3; Ny=4

my2Dlist= numpy.zeros((Nx,Ny)).tolist()

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

于 2016-07-14T08:55:42.253 回答

This answer is useful

6

采用:

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,以上是通用的。

于 2015-11-01T07:48:45.320 回答

This answer is useful

5

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

将比:

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

于 2018-11-18T14:02:10.853 回答

This answer is useful

4

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

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

于 2017-08-05T11:55:20.997 回答

This answer is useful

4

通过使用列表:

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:您需要处理哈希表中的冲突

于 2018-02-05T04:27:17.397 回答

This answer is useful

3

# Creates a list containing 5 lists initialized to 0

Matrix = [[0]*5]*5

小心这个简短的表达,在@FJ的回答中看到完整的解释

于 2014-02-08T10:24:14.897 回答

This answer is useful

2

以下是在 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=" ")

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

于 2019-12-09T12:54:17.767 回答

This answer is useful

2

通常,首选模块是 NumPy:

import numpy as np

# Generate a random matrix of floats

np.random.rand(cols,rows)

# Generate a random matrix of integers

np.random.randint(1, 10, size=(cols,rows))

于 2021-12-07T20:35:16.423 回答

This answer is useful

1

试试这个:

rows = int(input('Enter rows\n'))

my_list = []

for i in range(rows):

my_list.append(list(map(int, input().split())))

于 2018-12-28T08:45:03.540 回答

This answer is useful

1

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

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

于 2019-01-21T17:15:47.863 回答

This answer is useful

1

用户自定义函数输入矩阵和打印

def inmatrix(m,n):

#Start function and pass row and column as parameter

a=[] #create a blank matrix

for i in range(m): #Row input

b=[]#blank list

for j in range(n): # column input

elm=int(input("Enter number in Pocket ["+str(i)+"]["+str(j)+"] ")) #Show Row And column number

b.append(elm) #add value to b list

a.append(b)# Add list to matrix

return a #return Matrix

def Matrix(a): #function for print Matrix

for i in range(len(a)): #row

for j in range(len(a[0])): #column

print(a[i][j],end=" ") #print value with space

print()#print a line After a row print

m=int(input("Enter number of row")) #input row

n=int(input("Enter number of column"))

a=inmatrix(m,n) #call input matrix function

print("Matrix is ... ")

Matrix(a) #print matrix function

于 2021-05-24T11:35:40.880 回答