如何"很好地"在Python中打印列表

TIM*_*MEX 72 python

在PHP中,我可以这样做:

echo '<pre>'
print_r($array);
echo '</pre>'
Run Code Online (Sandbox Code Playgroud)

在Python中,我目前只是这样做:

print the_list
Run Code Online (Sandbox Code Playgroud)

但是,这将导致大量数据.有没有办法将它很好地打印到可读的树中?(有缩进)?

Joh*_*ooy 138

from pprint import pprint
pprint(the_list)
Run Code Online (Sandbox Code Playgroud)

  • @ clankill3r,然后你需要使用`pprint.pprint(the_list)`通常这只是个人喜好的问题.在这种情况下,我选择在导入行中有额外的混乱. (13认同)
  • 为什么不使用`import pprint`? (5认同)
  • @Mawg,您可以使用`stream =`指定输出流,默认为stdout.https://docs.python.org/3/library/pprint.html (2认同)

shx*_*fee 28

调试无需导入即可快速入侵,pprint可以加入列表'\n'.

>>> lst = ['foo', 'bar', 'spam', 'egg']
>>> print '\n'.join(lst)
foo
bar
spam
egg
Run Code Online (Sandbox Code Playgroud)

  • 当您的列表包含字符串以外的内容时,您应该执行 `print '\n'.join(map(str, lst))` (2认同)

Ale*_*lli 19

你的意思是......

>>> print L
['this', 'is', 'a', ['and', 'a', 'sublist', 'too'], 'list', 'including', 'many', 'words', 'in', 'it']
>>> import pprint
>>> pprint.pprint(L)
['this',
 'is',
 'a',
 ['and', 'a', 'sublist', 'too'],
 'list',
 'including',
 'many',
 'words',
 'in',
 'it']
>>> 
Run Code Online (Sandbox Code Playgroud)

...?从您的粗略描述,标准库模块pprint是第一个想到的东西; 但是,如果您可以描述示例输入和输出(以便不必学习PHP以帮助您;-),我们可能会提供更具体的帮助!


Mar*_*coP 17

只需通过"解压缩"print函数参数中的列表并使用换行符(\n)作为分隔符.

print(*lst,sep ='\n')

lst = ['foo', 'bar', 'spam', 'egg']
print(*lst, sep='\n')

foo
bar
spam
egg
Run Code Online (Sandbox Code Playgroud)

  • **“*”至关重要**,让我等一下 x) (4认同)
  • IMO 在 2021 年,Python 3 是标准,这应该是公认的答案 (4认同)
  • 不错,但不幸的是仅在Python 3中可用。 (2认同)
  • 如果你在 Python 2.7 中确实需要它,你仍然可以从 __future__ `from __future__ import print_function` 导入打印函数,感谢您的评论。 (2认同)

Eya*_*vin 9

import json
some_list = ['one', 'two', 'three', 'four']
print(json.dumps(some_list, indent=4))
Run Code Online (Sandbox Code Playgroud)

输出:

[
    "one",
    "two",
    "three",
    "four"
]
Run Code Online (Sandbox Code Playgroud)