漂亮的打印 Python 列表

Pretty print Python Lists

我在 python 中编写了一个 CLI 实用程序,我有一个包含 1:M 路径列表项的列表,例如:

我想以更 readable manner 的方式显示列表:

[
(1, '/path/here'), ('path/here/again'), 
(2, 'a/different/path/here'), ('another/path/here')
]

table-like 格式(例如):

1    /path/here                path/here/again
2    a/different/path/here     another/path/here

请注意,此列表可能包含 20 个或更多列表项。

谢谢!

开始:

>>> mylist = [
... (1, '/path/here', 'path/here/again'),
... (2, 'a/different/path/here', 'another/path/here')
... ]

join()map()str(),以及 Python 3 的 print() 功能:

>>> print(*('\t'.join(map(str, item)) for item in mylist), sep='\n')
1       /path/here      path/here/again
2       a/different/path/here   another/path/here

或者您可以尝试使用字符串格式代替 join()map():

>>> print(*(str(col) + '\t' + (len(item)*'{}').format(*(i.ljust(25) for i in item)) for col,*item in mylist), sep='\n')
1       /path/here               path/here/again
2       a/different/path/here    another/path/here

您还可以查看 pprint 模块。