python - 打印按长度包装的列网格
问题描述
我正在尝试以将每列的长度包装到该列中最长单词的长度(加上 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))))
我需要添加/更改什么来阻止它删除不完整的列?
解决方案
问题似乎出在这一行:
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'
为''
推荐阅读
- c++ - C++ ^ 运算符与函数一起使用
- html - 在网页中制作图表
- java - 如何捕获 GWT TextBox KeyDown 重复
- audio - 如何将音频文件设置为某些特征?
- flutter - Flutter PlatformException(error, 新嵌入不支持旧 FlutterView., null)
- javascript - 使用 javascript 从文本中获取 DOM 正文
- ios - 尝试使用后台任务在 10 秒后检索粘贴板值
- r - R闪亮的r-markdown:同步放大图表
- r - 无法在不覆盖的情况下将 R 数据框插入现有 Excel 文件
- python - 在 Matplotlib 中创建 pdp 图的子图