如何在Python中制作矩阵? [英] How to make matrices in Python?

查看:166
本文介绍了如何在Python中制作矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对其进行了搜索,并搜索了StackOverflow和YouTube.有人可以帮帮我吗?我只是想创建一个显示以下内容的基本5x5框:

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:

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

我知道了

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

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

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.

请某人帮助我,即使您将我引导到应该很明显的地方并使我看起来像个白痴,我也只是想学习这一点.

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.

推荐答案

循环帮助:

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

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

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

演示:

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

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

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 *args syntax lets you apply a whole sequence of rows as separate arguments:

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

这篇关于如何在Python中制作矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆