如何在列表中添加新行?

时间:2019-08-21 04:57:13

标签: python list

我要在创建列表时换行。

我尝试使用此代码来制作带有列表的图表。

[[[] for i in range(3)] for i in range(4)]

[[[], [], []], [[], [], []], [[], [], []], [[], [], []]]

但是我要打印的是

[[[], [], []], 
[[], [], []], 
[[], [], []], 
[[], [], []]]

,我不知道如何在此代码中添加“ \ n”。 谢谢:)

2 个答案:

答案 0 :(得分:7)

使用pprint

>>> from pprint import pprint
>>> pprint([[[] for i in range(3)] for i in range(4)], width=30)
[[[], [], []],
 [[], [], []],
 [[], [], []],
 [[], [], []]]
>>> 

答案 1 :(得分:0)

您可以尝试:

a = [[[] for i in range(3)] for i in range(4)]
sep = ',\n'
print(f"[{sep.join(str(e) for e in a)}]")

输出:

[[[], [], []],
[[], [], []],
[[], [], []],
[[], [], []]]