python - 如何在 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 模块可以让我相对轻松地实现我想要的,而不需要某种令人费解的黑客攻击?
谢谢
解决方案
您可以使用以下代码:
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
函数的一个很好的用例。可以使用它来缩短所有内容;)
推荐阅读
- javascript - 有没有办法在 Google App Script 中使用 python 函数?
- c# - 为什么图表不更新
- abp - 如何在 ABP 框架中禁用事务?
- docusignapi - 基于模板将文档添加到信封
- javascript - 使用 jQuery ajax 和 Django 上传文件
- c# - 如何修复数学随机方法组浮动
- javascript - 如何创建创建新 html 文件的函数/方法?
- javascript - 如何使用 Vuejs 中的链接重定向到另一个组件?
- python - 使用 python (tabula) 将 PDF 导出为 csv
- java - 需要帮助使用带括号和 OR 操作的正则表达式