2010-12-05 84 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