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