首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何计算最佳列宽?

如何计算最佳列宽?
EN

Stack Overflow用户
提问于 2010-12-05 11:53:08
回答 1查看 342关注 0票数 0

我有一小组列数据值,希望以可变宽度显示。一列具有较小的合理大小范围(例如,8-10个字符),一列显示UUID (总是36个字符),其他列是可变长度的标识符。

我希望最大限度地增加我可以显示的数据量,因为预计终端可能会窄到72个字符,宽到400个字符。

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

我该如何计算呢?

我正在使用python,如果这对任何人都有影响的话。

EN

回答 1

Stack Overflow用户

发布于 2010-12-05 22:00:52

代码语言:javascript
运行
复制
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)))

示例:

代码语言:javascript
运行
复制
data = [["some", "data", "here"], ["try", "to", "fit"], ["it", "on", "a screen"]]
align(data, 15)
>>> some data here 
>>> try  to   fit  
>>> it   on   a scr
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4357275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档