【问题标题】:How can I calculate optimal column widths?如何计算最佳列宽?
【发布时间】:2010-12-05 22:00:51
【问题描述】:

我有一小组列数据值,我想在可变宽度显示中显示。一列具有小范围的合理大小(例如,8-10 个字符),一列显示 UUID(始终为 36 个字符),其他列是可变长度标识符。

我想最大化我可以显示的数据量,因为终端可能会窄至 72 个字符,宽至大约 400 个字符。

超出其指定列宽的值将被缩写。

我应该如何计算这个?

我正在使用 python,如果它对任何人都很重要。

【问题讨论】:

  • 我认为您需要更具体地了解您的问题。为什么不按某种顺序分配列,直到填满可用宽度?

标签: python algorithm layout ncurses


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-28
    • 2017-12-20
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2011-10-07
    相关资源
    最近更新 更多