程序以多少行开头?有多少coloumns?每个coloumn的对齐?(左(L),中(C),右(R))。然后从用户接受条目(表中的数据)。条目应以用户指定的格式打印?以下是我到目前为止所做的事情:
rows = input("How many rows?")
coloumns = input("How many coloumns?")
alignment = raw_input("Enter alignment of each table?")
entry = raw_input("Enter rows x cols entries:")
print entry
我认为我必须以这样的方式格式化条目,以确切地说明用户想要的方式。我该怎么做?感谢
答案 0 :(得分:0)
从http://ginstrom.com/scribbles/2007/09/04/pretty-printing-a-table-in-python/引用的此代码块将对您有所帮助。
import locale
locale.setlocale(locale.LC_NUMERIC, "")
def format_num(num):
"""Format a number according to given places.
Adds commas, etc. Will truncate floats into ints!"""
try:
inum = int(num)
return locale.format("%.*f", (0, inum), True)
except (ValueError, TypeError):
return str(num)
def get_max_width(table, index):
"""Get the maximum width of the given column index"""
return max([len(format_num(row[index])) for row in table])
def pprint_table(out, table):
"""Prints out a table of data, padded for alignment
@param out: Output stream (file-like object)
@param table: The table to print. A list of lists.
Each row must have the same number of columns. """
col_paddings = []
for i in range(len(table[0])):
col_paddings.append(get_max_width(table, i))
for row in table:
# left col
print >> out, row[0].ljust(col_paddings[0] + 1),
# rest of the cols
for i in range(1, len(row)):
col = format_num(row[i]).rjust(col_paddings[i] + 2)
print >> out, col,
print >> out
table = [["", "taste", "land speed", "life"],
["spam", 300101, 4, 1003],
["eggs", 105, 13, 42],
["lumberjacks", 13, 105, 10]]
import sys
out = sys.stdout
pprint_table(out, table)
在您的情况下,因为您正在收集表格中的行,列,对齐和条目的输入,您可以将它们插入以构建您的table
变量。
rjust
和ljust
方法动态计算。