可変幅表示で表示したい列データ値の小さなセットがあります。1 つの列には妥当なサイズ (たとえば 8 ~ 10 文字) の狭い範囲があり、1 つの列には UUID (常に 36 文字) が表示され、他の列は可変長の識別子です。
端末の幅は 72 文字、幅は約 400 文字と予想されるため、表示できるデータの量を最大化したいと考えています。
割り当てられた列幅を超える値は省略されます。
これはどのように計算すればよいですか?
誰にとっても重要な場合、私はpythonを使用しています。
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