漂亮的打印Python列表

时间:2015-07-11 02:59:31

标签: python list formatting

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

我希望在更多BigQuery error in load operation: Source path is not a file: /usr/pipe1 中显示列表:

readable manner

或以[ (1, '/path/here'), ('path/here/again'), (2, 'a/different/path/here'), ('another/path/here') ] 格式(例如):

table-like

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

谢谢!

1 个答案:

答案 0 :(得分:1)

开始:

>>> 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模块。