这个程序非常简单。在我的程序中,我根据用户输入的列数来创建一个幂表。例如,如果用户输入5表示行数,6表示列数,会出现一个表格,标题会告诉您有多少行以及有多少列,如下所示:
使用我现在的代码,功率表工作,但顶部列的标题没有对齐,即使我使它们的间距相同。另外,我还需要列标题下的下划线,如上所示。这是我的代码:
def main():
inputRows= 0
inputColumns= 0
while (inputRows < 2) or (inputRows > 12):
inputRows= int(input("Enter an integer value for rows between 2 and 12: "))
while (inputColumns < 2) or (inputColumns > 12):
inputColumns= int(input("Enter an integer value for columns between 2 and 12: "))
powerTable= buildTable(inputColumns, inputRows, inputColumns)
for i in range(inputRows):
print(i, end="|")
for j in range(inputColumns):
powerTable[i][j]= i**j
print("%8d" % powerTable[i][j], end= "|")
print()
def buildTable(inputColumns, rows, cols) :
table = [] # initialize the tabl
for i in range(rows) : # for each row
row = [0] * cols # create a row with cols values
table.append(row) # and append it to the end of the table
for i in range(inputColumns):
print("%8d" % i, end="|")
print()
return table
main()
感谢大家的建议。
答案 0 :(得分:0)
要创建维度行x列的表格,将值设置为零,您可以执行以下操作:
def build_table(rows, cols):
""" Create a table of rows x cols values set to 0. """
return [[0] * cols for _ in range(rows)]
例如:
>>> build_table(3, 5)
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
现在,如果您想创建乘法表,您可以执行以下操作:
def build_mul_table(rows, cols):
""" Calculate the *mul* table. """
return [[i * j for j in range(1, cols + 1)] for i in range(1, rows + 1)]
这相当于:
table = []
for i in range(1, rows + 1):
row = []
for j in range(1, cols + 1):
row.append(i * j)
table.append(row)
例如:
>>> build_mul_table(3, 5)
[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15]]
然后,您可以编写一个单独的函数来显示任何类型的表:
def print_table(table):
cols = len(table[0])
header = [" "] + ["{0:4d}".format(j) for j in range(1, cols + 1)]
print(" | ".join(header))
header = ["----"] + ["----" for j in range(1, cols + 1)]
print(" + ".join(header))
for i, row in enumerate(table, 1):
line = ["{0:4d}".format(i)] + ["{0:4d}".format(v) for v in row]
print(" | ".join(line))
结果:
print_table(build_mul_table(3, 5))
| 1 | 2 | 3 | 4 | 5
---- + ---- + ---- + ---- + ---- + ----
1 | 1 | 2 | 3 | 4 | 5
2 | 2 | 4 | 6 | 8 | 10
3 | 3 | 6 | 9 | 12 | 15