如何自动以表格方式格式化子列表?

how to format sublists in a tabular way automatically?

我有以下列表,其中包含子列表

tableData = [['apples', 'oranges', 'cherries', 'banana'],['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']]

我的目标是这样格式化它们

  apples    Alice     dogs
 oranges      Bob     cats
cherries    Carol    moose
  banana    David    goose

下面的代码可以做到这一点

In [55]: for nested_list in zip(*tableData):
             print("{:>9} {:>9} {:>9}".format(*nested_list))

然而让我烦恼的是我需要手动指定每个子列表的格式。

我一直在尝试寻找一种使用 for 循环自动执行此操作的方法,但我没有找到任何与如何执行此操作相关的内容。

欢迎任何提示。

谢谢。

这个怎么样:

for line in zip(*tableData):
    for word in line:
        print("{:>9}".format(word), end=' ')
    print()

说明


如果 print() 不存在,所有子列表将像这样放在一行中

  apples     Alice      dogs   oranges       Bob      cats  cherries     Carol     moose    banana     David     goose

print() 允许换行

如果您只想使用 {:>9} 作为具有任意列数的格式代码,试试这个:

fieldFormat = ' '.join(['{:>9}'] * len(tableData))
for nestedList in zip(*tableData):
    print(fieldFormat.format(*nestedList))

这只是创建了一个 {:>9} 格式说明符列表,一个用于 tableData 中的每一列,然后用空格将它们连接在一起。

如果你也想自动计算字段宽度,你可以这样做:

fieldWidths = [max(len(word) for word in col) for col in tableData]
fieldFormat = ' '.join('{{:>{}}}'.format(wid) for wid in fieldWidths)
for nestedList in zip(*tableData):
    print(fieldFormat.format(*nestedList))

fieldWidths 是从计算每列中每个单词的最大长度的列表理解生成的。来自内部:

(len(word) for word in col)

这是一个生成器,将生成 col 中每个单词的长度。

max(len(word) for word in col)

将生成器(或任何可迭代对象)输入 max 将计算可迭代对象生成的所有内容的最大值。

[max(len(word) for word in col) for col in tableData]

此列表理解生成 tableData.

中每列 col 数据中所有单词的最大长度

fieldFormat 然后通过将 fieldWidths 转换为格式说明符来生成。再次从内部:

'{{:>{}}}'.format(wid)

这会将 wid 格式转换为 {:>#} 格式。 {{ 是一种让格式说明符产生 { 的方法;同样,}} 产生 }。中间的 {} 实际上是用 wid.

格式化的
('{{:>{}}}'.format(wid) for wid in fieldWidths)

这是一个生成器函数,它为 fieldWidths 中列出的每个宽度执行上述格式设置。

fieldFormat = ' '.join('{{:>{}}}'.format(wid) for wid in fieldWidths)

这只是将这些格式与中间的空格连接在一起以创建 fieldFormat 格式说明符。