简体   繁体   English

如何计算最佳列宽?

[英]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. 一列的显示范围很小(例如8-10个字符),一列显示UUID(始终为36个字符),而另一列是可变长度标识符。

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. 我希望最大化显示的数据量,因为该终端可能希望窄到72个字符,宽到大约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. 我正在使用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)))

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM