如何在 Python 中制作矩阵?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19084476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:48:59  来源:igfitidea点击:

How to make matrices in Python?

pythonmatrix

提问by user2829468

I've googled it and searched StackOverflow and YouTube.. I just can't get matrices in Python to click in my head. Can someone please help me? I'm just trying to create a basic 5x5 box that displays:

我在谷歌上搜索并搜索了 StackOverflow 和 YouTube .. 我只是无法在 Python 中获得矩阵来点击我的脑海。有人可以帮帮我吗?我只是想创建一个基本的 5x5 框,显示:

A A A A A
B B B B B
C C C C C
D D D D D
E E E E E

I got

我有

a b c d e
a b c d e
a b c d e
a b c d e
a b c d e

To display but I couldn't even get them to break lines that, instead all they would appear as

显示,但我什至无法让他们打破行,而是他们会显示为

[['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E']]

And if I try to add \n to them or print "" etc it just doesn't work.. \n will display as 'A\n' and print will display before the matrix.

如果我尝试向它们添加 \n 或打印 "" 等,它就不起作用.. \n 将显示为 'A\n' 并且打印将显示在矩阵之前。

Please someone help me, even if you direct me to somewhere that should be really obvious and make me look like an idiot, I just want to learn this.

请有人帮助我,即使您将我引导到应该非常明显的地方并使我看起来像个白痴,我也只是想学习这个。

采纳答案by Martijn Pieters

Looping helps:

循环有助于:

for row in matrix:
    print ' '.join(row)

or use nested str.join()calls:

或使用嵌套str.join()调用:

print '\n'.join([' '.join(row) for row in matrix])

Demo:

演示:

>>> matrix = [['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E']]
>>> for row in matrix:
...     print ' '.join(row)
... 
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E
>>> print '\n'.join([' '.join(row) for row in matrix])
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E

If you wanted to show the rows and columns transposed, transpose the matrix by using the zip()function; if you pass each row as a separate argument to the function, zip()recombines these value by value as tuples of columns instead. The *argssyntax lets you apply a whole sequence of rows as separate arguments:

如果要显示转置的行和列,请使用zip()函数转置矩阵;如果您将每一行作为单独的参数传递给函数,则将zip()这些值按值重新组合为列元组。该*args语法允许您将整个行序列应用为单独的参数:

>>> for cols in zip(*matrix):  # transposed
...     print ' '.join(cols)
... 
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E

回答by beroe

The answer to your question depends on what your learning goals are. If you are trying to get matrices to "click" so you can use them later, I would suggest looking at a Numpy arrayinstead of a list of lists. This will let you slice out rows and columns and subsets easily. Just try to get a column from a list of lists and you will be frustrated.

你的问题的答案取决于你的学习目标是什么。如果您试图让矩阵“点击”以便稍后使用它们,我建议您查看 Numpyarray而不是列表列表。这将使您轻松地切出行和列以及子集。只需尝试从列表列表中获取一列,您就会感到沮丧。

Using a list of lists as a matrix...

使用列表列表作为矩阵...

Let's take your list of lists for example:

让我们以您的列表列表为例:

L = [list("ABCDE") for i in range(5)]

It is easy to get sub-elements for any row:

很容易获得任何行的子元素:

>>> L[1][0:3]
['A', 'B', 'C']

Or an entire row:

或整行:

>>> L[1][:]
['A', 'B', 'C', 'D', 'E']

But try to flip that around to get the same elements in column format, and it won't work...

但是尝试翻转它以获得列格式的相同元素,它不会起作用......

>>> L[0:3][1]
['A', 'B', 'C', 'D', 'E']

>>> L[:][1]
['A', 'B', 'C', 'D', 'E']

You would have to use something like list comprehension to get all the 1th elements....

您必须使用类似列表理解的方法来获取所有第 1 个元素....

>>> [x[1] for x in L]
['B', 'B', 'B', 'B', 'B']

Enter matrices

输入矩阵

If you use an array instead, you will get the slicing and indexing that you expect from MATLAB or R, (or most other languages, for that matter):

如果您改为使用数组,您将获得您期望从 MATLAB 或 R(或大多数其他语言,就此而言)的切片和索引:

>>> import numpy as np
>>> Y = np.array(list("ABCDE"*5)).reshape(5,5)
>>> print Y
[['A' 'B' 'C' 'D' 'E']
 ['A' 'B' 'C' 'D' 'E']
 ['A' 'B' 'C' 'D' 'E']
 ['A' 'B' 'C' 'D' 'E']
 ['A' 'B' 'C' 'D' 'E']]
>>> print Y.transpose()
[['A' 'A' 'A' 'A' 'A']
 ['B' 'B' 'B' 'B' 'B']
 ['C' 'C' 'C' 'C' 'C']
 ['D' 'D' 'D' 'D' 'D']
 ['E' 'E' 'E' 'E' 'E']]

Grab row 1 (as with lists):

抓取第 1 行(与列表一样):

>>> Y[1,:]
array(['A', 'B', 'C', 'D', 'E'], 
      dtype='|S1')

Grab column 1 (new!):

抓取第 1 列(新!):

>>> Y[:,1]
array(['B', 'B', 'B', 'B', 'B'], 
      dtype='|S1')

So now to generate your printed matrix:

所以现在生成你的打印矩阵:

for mycol in Y.transpose():
    print " ".join(mycol)


A A A A A
B B B B B
C C C C C
D D D D D
E E E E E

回答by code

you can also use append function

您还可以使用附加功能

b = [ ]

for x in range(0, 5):
    b.append(["O"] * 5)

def print_b(b):
    for row in b:
        print " ".join(row)

回答by svs

you can do it short like this:

你可以像这样简短:

matrix = [["A, B, C, D, E"]*5]
print(matrix)


[['A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E']]

回答by J.Gaws

I got a simple fix to this by casting the lists into strings and performing string operations to get the proper print out of the matrix.

通过将列表转换为字符串并执行字符串操作以从矩阵中正确打印出来,我得到了一个简单的解决方法。

Creating the function

创建函数

By creating a function, it saves you the trouble of writing the forloop every time you want to print out a matrix.

通过创建函数,它可以省去for每次要打印矩阵时编写循环的麻烦。

def print_matrix(matrix):
    for row in matrix:
        new_row = str(row)
        new_row = new_row.replace(',','')
        new_row = new_row.replace('[','')
        new_row = new_row.replace(']','')
        print(new_row)

Examples

例子

Example of a 5x5 matrix with 0as every entry:

0每个条目都为 5x5 矩阵的示例:

>>> test_matrix = [[0] * 5 for i in range(5)]
>>> print_matrix(test_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 

Example of a 2x3 matrix with 0as every entry:

0每个条目都为 2x3 矩阵的示例:

>>> test_matrix = [[0] * 3 for i in range(2)]
>>> print_matrix(test_matrix)
0 0 0
0 0 0


EDIT

编辑

If you want to make it print:

如果你想让它打印:

A A A A A
B B B B B
C C C C C
D D D D D 
E E E E E

I suggest you just change the way you enter your data into your lists within lists. In my method, each list within the larger list represents a line in the matrix, not columns.

我建议您更改将数据输入到列表中的列表的方式。在我的方法中,较大列表中的每个列表代表矩阵中的一行,而不是列。

回答by Ganga Manoj

If you don't want to use numpy, you could use the list of lists concept. To create any 2D array, just use the following syntax:

如果您不想使用 numpy,则可以使用列表概念列表。要创建任何二维数组,只需使用以下语法:

  mat = [[input() for i in range (col)] for j in range (row)]

and then enter the values you want.

然后输入您想要的值。