【问题标题】:Python: Print new lines for each item in listPython:为列表中的每个项目打印新行
【发布时间】:2017-01-03 22:59:03
【问题描述】:

我的列表包含日期和日期之后的每个时间都在同一个子列表中。

[['2017-01-01', ['List 0', 'List 1', 'List 2']], ['2017-01-02', ['List 0', 'List 1', 'List 2']], ['2017-01-03', ['List 0', 'List 1', 'List 2']], 

我想做一个打印语句,它为每个日期打印一个新行,并为子列表中的每个项目打印一个新行,如下所示:

我尝试了几件事,例如:

def printList(self):
        print(*self.dataList, sep='\n')

它为每个日期打印一个新行,但我还希望子列表中的每个项目都有一个新行。

【问题讨论】:

  • 这是某个任务的一部分吗?如果没有,你为什么要这样做?

标签: python list printing


【解决方案1】:

试试标准库中的pprint

import pprint

dataList = [['2017-01-01', ['List 0', 'List 1', 'List 2']], ['2017-01-02', ['List 0', 'List 1', 'List 2']], ['2017-01-03', ['List 0', 'List 1', 'List 2']]]
pprint.pprint(dataList, width=30)

结果:

[['2017-01-01',
  ['List 0',
   'List 1',
   'List 2']],
 ['2017-01-02',
  ['List 0',
   'List 1',
   'List 2']],
 ['2017-01-03',
  ['List 0',
   'List 1',
   'List 2']]]

您可能需要使用width 参数。另见pprint.pformat()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多