假设 Python 2,我写了一个函数pprint_multiline,你可以随意自定义。
您可以自定义以下内容:
- 行长
- 项目之间的分隔符
- 行间分隔符(空字符串表示两行之间的空行,
None 表示根本没有行分隔符)
- 每个项目的对齐方式,以及
- 对齐字符。
该函数接受要水平打印的列表列表,因此您需要在调用该函数之前解压缩字典,如下面的示例所示。
这适用于字典中的任何值,假设它实现了__str__ 函数(大多数 Python 对象都这样做)。
功能:
def pprint_multilines(linelen=80, separator=' ', line_separator=None,
align='left', align_char=' ', lists=[]):
maxlen = max(len(lst) for lst in lists)
printed_lines = ['']*len(lists)
empty = True
printed = False
for i in xrange(maxlen):
max_item_len = max(len(str(lst[i])) for lst in lists)
if max_item_len + len(printed_lines[0]) + 1 > linelen:
if printed and line_separator is not None:
if len(line_separator) > 0:
print line_separator*(linelen/len(line_separator))
else:
print
for printed_line in printed_lines:
print printed_line
printed = True
printed_lines = ['']*len(lists)
empty = True
for lst_idx, lst in enumerate(lists):
if not empty:
printed_lines[lst_idx] += separator
if align == 'left':
printed_lines[lst_idx] += str(lst[i]).ljust(max_item_len, align_char)
else: # align == 'right'
printed_lines[lst_idx] += str(lst[i]).rjust(max_item_len, align_char)
else:
empty = False
if not empty:
if printed and line_separator is not None:
if len(line_separator) > 0:
print line_separator*(linelen/len(line_separator))
else:
print
for printed_line in printed_lines:
print printed_line
要查看它的实际效果,您可以查看以下示例:
dict1 = {'a': 'first', 'b': 'second', 'c': 3, 'd': ['the', 'fourth']}
dict2 = {'a': 1, 'b':2, 'c':3, 'd':4}
dict3 = {'a': '1', 'b':'two', 'c':'three', 'd': 'fourth'}
list_of_keys = ['a','b','c','d']
pprint_multilines(linelen=15, separator=' ', align='left', align_char=' ',
line_separator='-',
lists=[[dict1[key] for key in list_of_keys],
[dict2[key] for key in list_of_keys],
[dict3[key] for key in list_of_keys]])
print
pprint_multilines(linelen=15, separator=' ', align='left', align_char=' ',
lists=[[dict1[key] for key in list_of_keys],
[dict2[key] for key in list_of_keys],
[dict3[key] for key in list_of_keys]])
print
pprint_multilines(linelen=25, separator=' ', align='left', align_char=' ',
line_separator='',
lists=[[dict1[key] for key in list_of_keys],
[dict2[key] for key in list_of_keys],
[dict3[key] for key in list_of_keys]])
print
pprint_multilines(linelen=45, separator=' ', align='left', align_char='_',
lists=[[dict1[key] for key in list_of_keys],
[dict2[key] for key in list_of_keys],
[dict3[key] for key in list_of_keys]])
print
pprint_multilines(linelen=45, separator=' ', align='right', align_char=' ',
lists=[[dict1[key] for key in list_of_keys],
[dict2[key] for key in list_of_keys],
[dict3[key] for key in list_of_keys]])
将输出(带有一些 cmets):
第一秒
1 2
1 两个
---------------