2010-12-05 86 views
0

我有一个小集,我想在一个宽度可变的显示器显示的列数据值。一列有一个小的范围内合理的尺寸(比如,8-10个字符),一个显示一个UUID(总是36个字符),而其它的是可变长度标识符。如何计算最佳色谱柱宽度?

我希望最大化数据I可以显示的,鉴于终端可以被预期为作为72个字符窄和一样宽大约400

值超过他们的分配列宽度将是量缩写。

我应该如何计算呢?

我使用python,如果它关系到人。

+0

我认为你需要更具体的了解你的问题是什么。为什么不直接按照某种顺序分配列,直到填充可用宽度为止? – 2010-12-05 11:38:57

回答

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