如何“精巧”地在Python中打印列表


88

在PHP中,我可以这样做:

echo '<pre>'
print_r($array);
echo '</pre>'

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

print the_list

但是,这将导致大量数据。有什么方法可以将其很好地打印到可读的树中吗?(带有缩进)?

Answers:


167
from pprint import pprint
pprint(the_list)

如何漂亮地打印到文件?
Mawg说恢复Monica

5
为什么不只是使用import pprint
clankill3r

18
@ clankill3r,那么您pprint.pprint(the_list)通常需要使用只是个人喜好问题。在这种情况下,我选择在导入行中增加额外的混乱。
John La Rooy

2
@Mawg,您可以使用指定输出流stream=,默认为stdout。docs.python.org/3/library/pprint.html
John La Rooy

它在Ipython REPL中默认启用
azzamsa

31

无需导入即可进行调试的快速调试pprint方法是加入上的列表'\n'

>>> lst = ['foo', 'bar', 'spam', 'egg']
>>> print '\n'.join(lst)
foo
bar
spam
egg

列表包含时发生TypeError None
Noumenon

简单的解决方案,可以像`“ list:* {}”。format('\ n *'
join

当你的列表中包含一些其他的字符串,然后你应该做的print '\n'.join(map(str, lst))
精神

24

只需通过“打开”打印函数参数中的列表并使用换行符(\ n)作为分隔符即可。

打印(* lst,sep ='\ n')

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

foo
bar
spam
egg

2
尼斯可惜只在Python 3可
安东尼拉巴尔

1
如果您确实在Python 2.7中需要它,您仍然可以从以后 导入print函数。from __future__ import print_function 感谢您的评论。
MarcoP

21

您的意思是……:

>>> 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']
>>> 

...?从您的粗略描述中,首先想到的是标准库模块pprint。但是,如果您可以描述示例输入和输出(这样就不必为了帮助您而学习PHP ;-),那么我们就有可能提供更具体的帮助!




2

其他答案表明pprint模块可以解决问题。
但是,在进行调试的情况下,您可能需要将整个列表放入某个日志文件中,因此可能必须使用pformat方法以及模块日志记录和pprint。

import logging
from pprint import pformat

logger = logging.getLogger('newlogger')
handler = logging.FileHandler('newlogger.log')

formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)

logger.addHandler(handler) 
logger.setLevel(logging.WARNING)

data = [ (i, { '1':'one',
           '2':'two',
           '3':'three',
           '4':'four',
           '5':'five',
           '6':'six',
           '7':'seven',
           '8':'eight',
           })
         for i in xrange(3)
      ]

logger.error(pformat(data))

而且,如果您需要直接将其记录到文件中,则必须使用stream关键字指定输出流。参考

from pprint import pprint

with open('output.txt', 'wt') as out:
   pprint(myTree, stream=out)

参见Stefano Sanfilippo的答案


2

对于Python 3,我做与shxfee的回答相同的事情:

def print_list(my_list):
    print('\n'.join(my_list))

a = ['foo', 'bar', 'baz']
print_list(a)

哪个输出

foo
bar
baz

顺便说一句,我使用类似的辅助函数来快速查看pandas DataFrame中的列

def print_cols(df):
    print('\n'.join(df.columns))

0

正如其他答案所提到的, pprint一个很棒的模块可以满足您的需求。但是,如果您不想导入它,而只想在开发过程中打印调试输出,则可以近似其输出。

其他一些答案对于字符串也可以正常工作,但是如果您对类对象尝试使用它们,则会出错TypeError: sequence item 0: expected string, instance found

对于更复杂的对象,请确保该类具有__repr__打印所需属性信息的方法:

class Foo(object):
    def __init__(self, bar):
        self.bar = bar

    def __repr__(self):
        return "Foo - (%r)" % self.bar

然后,当您要打印输出时,只需将列表映射到如下str函数:

l = [Foo(10), Foo(20), Foo("A string"), Foo(2.4)]
print "[%s]" % ",\n ".join(map(str,l))

输出:

 [Foo - (10),
  Foo - (20),
  Foo - ('A string'),
  Foo - (2.4)]

您还可以执行诸如覆盖__repr__方法的方法,list以获取嵌套的漂亮打印形式:

class my_list(list):
    def __repr__(self):
        return "[%s]" % ",\n ".join(map(str, self))

a = my_list(["first", 2, my_list(["another", "list", "here"]), "last"])
print a

[first,
 2,
 [another,
 list,
 here],
 last]

不幸的是,没有二级缩进,但是对于快速调试它可能是有用的。


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.