首页 > 解决方案 > 如何在 Python 3.6 中根据需要打印一组嵌套列表

问题描述

我有一个嵌套的包含不同长度的值,如下所示:

[['cat', 123, 'yellow'],
['dog', 12345, 'green'],
[horse', 123456, 'red']]

我想像这样打印它们:

cat,   123,    yellow
dog,   12345,  green
horse, 123456, red 

我尝试使用 pprint 通过以下代码实现我的目标:

for sub in master_list:

    pp = pprint.PrettyPrinter(indent=4)
    pp.pprint(sub)

其中 master 是嵌套列表,并且是其中的子列表。然而,这给了我这样的输出:

[
    'cat', 
    123, 
    'yellow'
],

[
    'dog', 
    12345, 
    'green'
],

[
    horse', 
    123456, 
    'red'
]

是否有一个 python 模块可以让我相对轻松地实现我想要的,而不需要某种令人费解的黑客攻击?

谢谢

标签: pythonpython-3.xpython-3.6

解决方案


您可以使用以下代码:

myLst = [['cat', 123, 'yellow'],
['dog', 12345, 'green'],
['horse', 123456, 'red']]

for subLst in myLst:
    print("\t".join([str(ele) for ele in subLst]))

像这样打印输出:

cat    123      yellow
dog    12345    green
horse  123456   red

如果您也想有“,”,只需更改行

print("\t".join([str(ele) for ele in subLst]))

print(",\t".join([str(ele) for ele in subLst]))

完整的单线:

print("\n".join([",\t".join([str(ele) for ele in subLst]) for subLst in myLst]))

或者如果您需要一个功能:

def printLst(myLst):
    print("\n".join([",\t".join([str(ele) for ele in subLst]) for subLst in myLst]))

编辑

正如评论中所指出的,这也是 pythonmap函数的一个很好的用例。可以使用它来缩短所有内容;)


推荐阅读