如何计算最佳色谱柱宽度?

时间:2010-12-05 03:53:08

标签: python algorithm layout ncurses

我想要在可变宽度显示中显示一小组列数据值。一列有一小部分似乎合理的大小(比如8-10个字符),一列显示UUID(总是36个字符),其他列是可变长度标识符。

我想最大化我可以显示的数据量,因为终端可能会被缩小到72个字符,宽到大约400个。

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

我该如何计算?

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

1 个答案:

答案 0 :(得分: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