如何在Python的分隔行中打印列表元素(也是列表) [英] How to print list elements (which are also lists) in separated lines in Python

查看:832
本文介绍了如何在Python的分隔行中打印列表元素(也是列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经检查了SO帖子上的帖子和答案 在Python中的分隔行上打印列表元素 ,而我认为我的问题是另外一个问题.

I've checked the post and answers on the SO post Printing list elements on separated lines in Python, while I think my problem is a different one.

我想要的是变换:

lsts = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]

进入如下所示的输出:

[[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1]]

我尝试追加,在for循环中打印 和"\ n" .join(),但都失败了.

I tried append, print in the for loop and "\n".join() but all failed.

推荐答案

要完全实现所需的效果,可以像已经建议的那样手动展开并打印外部数组:

To achieven exactly what you want, you could manually unroll and print the outer array like already suggested:

>>> lsts = [[1], [2,3], [4, 5, 6]]
>>> print("[" + ",\n".join(str(i) for i in lsts) + "]")
[[1],
[2, 3],
[4, 5, 6]]

并非完全符合您的要求,但 json.dumps 可以通过指定indent做一些漂亮的打印:

Not exactly what you requested, but json.dumps can do some pretty-printing by specifying an indent:

>>> print(json.dumps(lsts, indent=4))
[
    [
        1
    ],
    [
        2,
        3
    ],
    [
        4,
        5,
        6
    ]
]

然后有 pprint ,用于人类的智能打印:

And then there's pprint, which is intended for somewhat intelligent printing for humans:

>>> pprint(lsts, width=20)
[[1],
 [2, 3],
 [4, 5, 6]]

这篇关于如何在Python的分隔行中打印列表元素(也是列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆