首页 > 解决方案 > 打印按长度包装的列网格

问题描述

我正在尝试以将每列的长度包装到该列中最长单词的长度(加上 2 个空格填充)的格式打印一个二维列表。我试图在下面实现的示例:

t1      thing2   t3            t4
thing5  t6       thingymajig7  thing8
thing9  thing10

目前,我的代码几乎实现了这一点,但如果有一行少于其中的最大项目数,它会不断剪掉最后的“n”列。下面的例子:

t1      thing2
thing5  t6
thing9  thing10

到目前为止,这是我的代码的一部分:

rows = [[thing1, thing2, thing3, t4], [t5, t6, thingymajig7, thing8], [thing9, thing10]]

widths = [max(len(item) for item in col) for col in zip(*rows)]

for r in rows:
    print("  ".join((item.ljust(width) for item, width in zip(r, widths))))

我需要添加/更改什么来阻止它删除不完整的列?

标签: pythonpython-3.xmultidimensional-arrayprintingformatting

解决方案


问题似乎出在这一行:

widths = [max(len(item) for item in col) for col in zip(*rows)]

来自 zip 上的文档:https ://docs.python.org/3/library/functions.html#zip

当最短的输入迭代用完时,迭代器停止。

因此,必须将每个列表rows延长到最长列表的长度才能使rows该脚本正常工作。您可以通过以下方式实现:

rows = [['thing1', 'thing2', 'thing3', 't4'], ['t5', 't6', 'thingymajig7', 'thing8'], ['thing9', 'thing10']]

max_row_len = len(max(rows, key=len))

for row in rows:
  row_len = len(row)
  row.extend(['blank' for f in range(max_row_len - row_len)])

widths = [max(len(item) for item in col) for col in zip(*rows)]

for r in rows:
    print("  ".join((item.ljust(width) for item, width in zip(r, widths))))

然后你可以替换'blank'''


推荐阅读