0

我有一小组列数据值,我想在可变宽度显示中显示。一列具有小范围的合理大小(例如,8-10 个字符),一列显示 UUID(始终为 36 个字符),其他列是可变长度标识符。

我想最大化我可以显示的数据量,因为终端可能预计窄至 72 个字符,宽至约 400 个字符。

超出其指定列宽的值将被缩写。

我应该如何计算这个?

我正在使用 python,如果它对任何人都很重要。

4

1 回答 1

1
def getMaxLen(xs):
    ys = map(lambda row: map(len, row), xs)
    return reduce(
        lambda row, mx: map(max, zip(row,mx)),
        ys)

def formatElem((e, m)):
    return e[0:m] + " "*(m - len(e))

# reduceW is some heuristic that will try to reduce
# width of some columns to fit table on a screen.
# This one is pretty inefficient and fails on too many narrow columns.
def reduceW(ls, width):
    if len(ls) < width/3:
        totalLen = sum(ls) + len(ls) - 1
        excess = totalLen - width
        while excess > 0:
            m = max(ls)
            n = max(2*m/3, m - excess)
            ls[ls.index(m)] = n
            excess = excess - m + n
    return ls


def align(xs, width):
    mx = reduceW(getMaxLen(xs), width)
    for row in xs:
        print " ".join(map(formatElem, zip(row, mx)))

例子:

data = [["some", "data", "here"], ["try", "to", "fit"], ["it", "on", "a screen"]]
align(data, 15)
>>> some data here 
>>> try  to   fit  
>>> it   on   a scr
于 2010-12-05T14:00:51.863 回答