2010-12-05 19 views
0

私は可変幅表示で表示したい小さな列データ値を持っています。 1つの列は、考えられるサイズ(例えば、8〜10文字)の小さな範囲を持ち、1つはUUID(常に36文字)を表示し、その他は可変長の識別子です。最適な列幅はどのように計算できますか?

私は、端末は、割り当てられた列の幅を超えておよそ400

値がされると同じ幅の72文字だけ狭くなると予想してすることができることを考えると、私が表示できるデータの量を最大にしたいです略語。

これはどのように計算すればよいですか?

私は誰にとっても重要なPythonを使用しています。

+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 
関連する問題