将打印的列填充为窗口大小

时间:2018-08-02 16:24:09

标签: python dynamic printing formatting window

现在,我现在有一段代码,该代码接受一个字符串列表,并输出整洁的列,每列之间有两个空格,如下所示:

thing1  t2       thing3        t4
thing5  thing6   thingymajig7  thing8
t9      thing10 

但是,我希望这些列能够一直填充到右边,以尽可能多地适合。当前,在构建二维数组时,我已对硬编码的列数进行了编码。我在下面的代码中标记了特定的行:

rNum = 0
count = 1
rows = [[]]

# build 2-dimensional array
for item in result.split():
    if count%5 == 0:               # hard coded number of columns in each row
        rows[rNum].append(item)
        rows.append([])
        rNum += 1
    else:
        rows[rNum].append(item)
    count += 1

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

# extend rows to uniform length to work with zip()
for r in rows:
    rowLen = len(r)
    r.extend(["" for f in range(maxRowLen - rowLen)])
widths = [max(len(item) for item in col) for col in zip(*rows)]

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

我遇到的主要问题是,仅检查第一行是不可靠的,因为在较低行中具有较长字符串的任何列都会延长该列的长度。不幸的是,如果不先构建整个组件,我将无法检查每列的最大长度。

现在我正在考虑必须动态测试每个列数(最长到最短,对于较大的输入,从一个合理的数量开始),并在打印之前累加宽度,并继续尝试直到得到一个宽度适合。我希望有比这更优雅的解决方案。

预先感谢您的帮助!

0 个答案:

没有答案
相关问题