How to right-justify elements in a list?
本问题已经有最佳答案,请猛点这里访问。
我需要我的func打印出以下内容:
1 2 3 4 | apples Alice dogs oranges Bob cats cherries Carol moose banana David goose |
所有项目都右对齐
我有解决方案,但这是一个解决办法,你能帮我纠正我的方案吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printData(lst): colWidths = [0] * len(tableData) for a in range(len(tableData)): colWidths[a] = len(max(tableData[a], key=len)) for i in range(len(lst[0])): output = '' for j in range(len(lst)): output += (str(lst[j][i])).rjust(colWidths[0]) print(output) print(printData(tableData)) apples Alice dogs oranges Bob cats cherries Carol moose banana David goose |
您可以将格式规范迷你语言与
1 2 3 4 5 6 | tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] for tup in zip(*tableData): print("{:>9} {:>9} {:>9}".format(*tup)) |
印刷品
1 2 3 4 | apples Alice dogs oranges Bob cats cherries Carol moose banana David goose |
编辑:
如果在编写代码时不知道列的大小,可以动态生成这些字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from itertools import chain def gen_format_str(widths): return ' '.join(["{{:>{}}}".format(width) for width in widths]) def n_of_width(n, width): return gen_format_str([width] * n) def all_widest(list_of_lists): return n_of_width(len(list_of_lists), max(map(len, chain.from_iterable(list_of_lists)))) format_str = all_widest(tableData) for tup in zip(*tableData): print(format_str.format(*tup)) |
这样做:
1 | for index in range(len(tableData)): |
大约80%的时间是错误的。先用
在这种情况下:
1 2 3 4 5 6 7 8 9 10 | >>> tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] >>> fruits, persons, pets = tableData >>> for n,fruit in enumerate(fruits): print (f"{fruit:>8s} {persons[n]:>8s} {pets[n]:>8s}") apples Alice dogs oranges Bob cats cherries Carol moose banana David goose |
但这并不能处理扩展列宽以获得所需的最小空间量。要包含该优化,请计算列宽并将其包含在格式中:
1 2 3 4 5 6 7 8 | >>> widths = [max(len(x) for x in d) for d in tableData] >>> for n,fruit in enumerate(fruits): print (f"{fruit:>{widths[0]}s} {persons[n]:>{widths[1]}s} {pets[n]:>{widths[2]}s}") apples Alice dogs oranges Bob cats cherries Carol moose banana David goose |