2017-02-22 88 views
0

我有用户输入到我的程序中矩阵的程度(例如3x3 == X = 3,Y = 3)然后填充9个值列表会弥补我的3x3矩阵,像这样:如何打印python列表的元素看起来像一个矩阵

total = x * y # the x and y values inputted by the user 
    i = 1 
    while i <= total: 
     matrix.append(i) 
     i += 1 

后,我有这个矩阵填充我想打印出来,这样我打印值矩阵[0],[1],[2]的第一行和等等。但我想对于任何规模矩阵做到这一点,我已经试过这样:

i = 1 
j = 0 
while j < total: 
    print matrix[j] 
    if not i == x: 
     print '' 
     i += 1 
    else: 
     print '\n' 
     i = 1 
    j += 1 

,没有运气,因为它在新行打印每个值,而不管...任何帮助表示赞赏,谢谢!

+0

供将来参考,'if if not == == x:'也可以写成'if if i!= x:' – asongtoruin

回答

1

如何:

x = 3 
y = 3 

matrix = [[(i+1)+(j*x) for i in range(x)] for j in range(y)] 

for row in matrix: 
    print ' '.join(map(str, row)) 

打印:

1 2 3 
4 5 6 
7 8 9 

编辑:正如在评论中建议,我们可以把最后一行更加灵活,表现出适当的“矩阵”的格式如下:

for row in matrix: 
    print ' '.join(s.rjust(len(str(x*y)), ' ') for s in map(str, row)) 

这意味着无论x和y的大小如何,我们都会始终将我们的值隔开年。例如,如果x=6y=6,它会打印:

1 2 3 4 5 6 
7 8 9 10 11 12 
13 14 15 16 17 18 
19 20 21 22 23 24 
25 26 27 28 29 30 
31 32 33 34 35 36 

如果x=10y=10它会打印:

1 2 3 4 5 6 7 8 9 10 
11 12 13 14 15 16 17 18 19 20 
21 22 23 24 25 26 27 28 29 30 
31 32 33 34 35 36 37 38 39 40 
41 42 43 44 45 46 47 48 49 50 
51 52 53 54 55 56 57 58 59 60 
61 62 63 64 65 66 67 68 69 70 
71 72 73 74 75 76 77 78 79 80 
81 82 83 84 85 86 87 88 89 90 
91 92 93 94 95 96 97 98 99 100 

等。

+0

你可能会考虑'''.join(s.rjust('',2)for s in map(str,row))'或者sth。类似于混合多位数字 – schwobaseggl

+0

@schwobaseggl好主意 - 编辑它,灵活适用于任何大小的“x”和“y” – asongtoruin

0

您可以将

print "" 

print "", 

替换为了不换行添加到末尾。

或者,你可以使用python 3打印功能,它支持这个作为参数。要做到这一点,您应该导入__ future__并致电打印就像一个函数。请参阅下面的代码为例:

from __future__ import print_function 
print("my string", end = "") 

你可以阅读更多有关使用打印为对docs page的功能。

0

此答案根据this answer。该答案仅考虑形状。为了使它看起来像一个矩阵,你可以使用箱体字符。

c, x, y = 1, 3, 3 

matrix = [[(i+1)+(j*x) for i in range(x)] for j in range(y)] 

for row in matrix: 
    if c == 1: 
     print u'\u250F', ' '.join(s.rjust(len(str(x*y)), ' ') for s in map(str, row)), u'\u2513' 
    elif c-y == 0: 
     print u'\u2517', ' '.join(s.rjust(len(str(x*y)), ' ') for s in map(str, row)), u'\u251B' 
    else: 
     print u'\u2503', ' '.join(s.rjust(len(str(x*y)), ' ') for s in map(str, row)), u'\u2503' 
    c += 1 

另一种可能性是:

x, y = 3, 3 

matrix = [[(i+1)+(j*x) for i in range(x)] for j in range(y)] 

print u'\u250F', ''.join(((2*x)-2)*' '), u'\u2513' 
for row in matrix: 
    print u'\u2503', ' '.join(s.rjust(len(str(x*y)), ' ') for s in map(str, row)), u'\u2503' 
print u'\u2517', ''.join(((2*x)-2)*' '), u'\u251B' 

如果你想在CMD.EXE运行此,看到this question

相关问题