table = []
row_one = int(input("Enter row number:"))
column = int(input("Enter column number:"))
for j in range(1, row_one + 1):
for i in range(1, column + 1):
temp = []
temp.append(j * i)
table.append(temp)
print table
如果我的行和列分别是2乘2 我的输出看起来像:
[[1], [2], [2], [4]]
但是,它应该看起来像:
1 2
2 4
答案 0 :(得分:1)
我将temp=[]
移到内循环之外,table.append(temp)
移出内循环之外。所以表格如下:[[1,2],[2,4]]
。我还跟踪了最长的值,所以我知道在表格中填充多少空间。我将值转换为字符串,因为它看起来只是用于输出,但如果您需要引用表值,则可以在以后完成。
table = []
row_one = int(input("Enter row number:"))
column = int(input("Enter column number:"))
biggest=1
for j in range(1, row_one + 1):
temp=[]
for i in range(1, column + 1):
v=str(i*j)
temp.append(v)
if len(v)>biggest:
biggest=len(v)
table.append(temp)
for row in table:
t=[n+' '*(biggest-len(n)) for n in row]
print ' '.join(t)
输出(2,2输入)
1 2
2 4
输出(带有5,5输入 - 显示填充)
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
答案 1 :(得分:1)
这应该完全符合你的要求。对于不同的矩阵大小也是动态的
table = []
row_one = int(input("Enter row number:"))
column = int(input("Enter column number:"))
for j in range(row_one):
table.append([])
for i in range(column):
table[j].append((j+1) * (i+1))
for row in table:
for column in row:
if column != row[len(row) - 1]:
print column,
else:
print column
输出:
Enter row number:2
Enter column number:2
1 2
2 4
答案 2 :(得分:0)
import numpy as np
table = []
row_one = int(input("Enter row number:"))
column = int(input("Enter column number:"))
for j in range(1, row_one + 1):
for i in range(1, column + 1):
temp = []
temp.append(j * i)
table.append(temp)
print (np.reshape(table, (row_one, column)))
输出:
[[1 2]
[2 4]]
答案 3 :(得分:0)
您可以使用print_function
使用sep='\n'
进行打印。您可以使用某种格式删除[
,]
,但主要的想法就在这里。我还修了一个小错误,看看评论:
from __future__ import print_function
table = []
row_one = int(input("Enter row number:"))
column = int(input("Enter column number:"))
for j in range(1, row_one + 1):
temp = [] # temp need to be outside of the loop to work as intended
for i in range(1, column + 1):
temp.append(j * i)
table.append(temp) # note the identation of this
print(*table, sep='\n')
输出:
Enter row number:4
Enter column number:4
[1, 2, 3, 4]
[2, 4, 6, 8]
[3, 6, 9, 12]
[4, 8, 12, 16]
Bonus:必要的python one-liners
table = [[(j+1) * (i+1) for i in range(column)] for j in range(row_one)]
print(*(' '.join(map(str,line)) for line in table), sep='\n')