【问题标题】:Output formatting of a list列表的输出格式
【发布时间】:2018-04-05 01:23:23
【问题描述】:

在python中有一段代码:

print (sorted([(r,len(f)) for r,d,f in os.walk(directory_path)],key=lambda x : x[1],reverse = True))

输出如下:

[('/etc/ssl/certs', 595), ('/etc/alternatives', 109), ('/etc/', 73), ('/etc/init.d', 52),('/etc/dovecot/conf.d', 27)]

我想要类似的东西(不将其存储到变量中):

('/etc/ssl/certs', 595)
('/etc/alternatives', 109)
('/etc/', 73)
('/etc/init.d', 52)
('/etc/dovecot/conf.d', 27)]

【问题讨论】:

  • 只使用 pprint

标签: python os.walk output-formatting


【解决方案1】:

使用pprint

import pprint
pprint.pprint(sorted([(r,len(f)) for r,d,f in os.walk(directory_path)],key=lambda x : x[1],reverse = True))

pprint.pprint([('/etc/ssl/certs', 595), ('/etc/alternatives', 109), ('/etc/', 73), ('/etc/init.d', 52),('/etc/dovecot/conf.d', 27)])
# [('/etc/ssl/certs', 595),
#  ('/etc/alternatives', 109),
#  ('/etc/', 73),
#  ('/etc/init.d', 52),
#  ('/etc/dovecot/conf.d', 27)]

【讨论】:

    【解决方案2】:

    你有没有尝试过这样的事情?

    [print(str(x)) for x in sorted([(r,len(f)) for r,d,f in os.walk(directory_path)],key=lambda x : x[1],reverse = True)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2016-12-26
      • 2019-11-14
      • 2021-10-25
      • 2011-12-21
      • 2011-08-21
      • 1970-01-01
      相关资源
      最近更新 更多