开发者

How can I calculate optimal column widths?

I have a small set of column data values that I want to display in a开发者_开发知识库 variable-width display. One column has a small range of plausible sizes (say, 8-10 characters), one displays a UUID (always 36 chars), and the others are variable-length identifiers.

I want to maximize the amount of data I can display, given that the terminal may be expected to be as narrow as 72 characters and as wide as about 400.

Values that exceed their assigned column widths will be abbreviated.

How should I calculate this?

I'm using python, if it matters to anyone.


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)))

Example:

data = [["some", "data", "here"], ["try", "to", "fit"], ["it", "on", "a screen"]]
align(data, 15)
>>> some data here 
>>> try  to   fit  
>>> it   on   a scr
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜