Python的制表 - 配置如何格式化包含列表中的单元

问题描述 投票:0回答:2

我使用python-制表打印具有包含列表中的单元数据。我可以自定义的python-算算到底格式的单元格内容,所以列表被以不同的方式格式化?

我想避免手动预处理(列表转换为字符串)传递给制表的数据。

如果制表不会允许这样做,在哪里我可以定义更细粒度的格式选项有替代库?

示例代码:

from tabulate import tabulate

# Minimal sample. My output comes from an API and contains much more data
table = [['Sun', [1, 2, 3]], ['Moon', [4, 5, 6]]]
print(tabulate(table, tablefmt='plain', headers=['Planet', 'Value']))

输出:

Planet    Value
Sun       [1, 2, 3]
Moon      [4, 5, 6]

我多么想格式化输出:

Planet    Value
Sun       1,2,3
Moon      4,5,6
python tabulate
2个回答
2
投票

我建议你去尝试不同的库。我检查了DOC,并没有发现任何有关。

或有功能它(你没有要求它虽然)

from tabulate import tabulate

def delist(lst):
    return ",".join([str(item) for item in lst]) 

table = [['Sun', delist([1, 2, 3])], ['Moon', delist([4, 5, 6])]]
print(tabulate(table, tablefmt='plain', headers=['Planet', 'Value']))
>>>
Planet    Value
Sun       1,2,3
Moon      4,5,6

最后的选择,也许有点绝望......一个是采取类制成表格,并在其中集成该功能。但它有点大材小用


0
投票

因为我无法找到一个方法如何相应地配置的平板状,一个解决方案是猴子补丁以表格形式列出内部_format方法。

原始方法(制表0.8.2):

def _format(val, valtype, floatfmt, missingval="", has_invisible=True):
    """Format a value accoding to its type.

    Unicode is supported:

    >>> hrow = ['\u0431\u0443\u043a\u0432\u0430', '\u0446\u0438\u0444\u0440\u0430'] ; \
        tbl = [['\u0430\u0437', 2], ['\u0431\u0443\u043a\u0438', 4]] ; \
        good_result = '\\u0431\\u0443\\u043a\\u0432\\u0430      \\u0446\\u0438\\u0444\\u0440\\u0430\\n-------  -------\\n\\u0430\\u0437             2\\n\\u0431\\u0443\\u043a\\u0438           4' ; \
        tabulate(tbl, headers=hrow) == good_result
    True

    """
    if val is None:
        return missingval

    if valtype in [int, _text_type]:
        return "{0}".format(val)
    elif valtype is _binary_type:
        try:
            return _text_type(val, "ascii")
        except TypeError:
            return _text_type(val)
    elif valtype is float:
        is_a_colored_number = has_invisible and isinstance(val, (_text_type, _binary_type))
        if is_a_colored_number:
            raw_val = _strip_invisible(val)
            formatted_val = format(float(raw_val), floatfmt)
            return val.replace(raw_val, formatted_val)
        else:
            return format(float(val), floatfmt)
    else:
        return "{0}".format(val)

我修改的版本:

# tabulate_extensions.py
from tabulate import _text_type, _binary_type, _strip_invisible


def _format_extended(val, valtype, floatfmt, missingval="", has_invisible=True):
    """Format a value accoding to its type.

    Unicode is supported:

    >>> hrow = ['\u0431\u0443\u043a\u0432\u0430', '\u0446\u0438\u0444\u0440\u0430'] ; \
        tbl = [['\u0430\u0437', 2], ['\u0431\u0443\u043a\u0438', 4]] ; \
        good_result = '\\u0431\\u0443\\u043a\\u0432\\u0430      \\u0446\\u0438\\u0444\\u0440\\u0430\\n-------  -------\\n\\u0430\\u0437             2\\n\\u0431\\u0443\\u043a\\u0438           4' ; \
        tabulate(tbl, headers=hrow) == good_result
    True

    """
    if val is None:
        return missingval

    if valtype in [int, _text_type]:
        # Change list formatting [1,2,3] -> 1,2,3
        if type(val) == list:
            val = ','.join([str(x) for x in val])
        return "{0}".format(val)
    elif valtype is _binary_type:
        try:
            return _text_type(val, "ascii")
        except TypeError:
            return _text_type(val)
    elif valtype is float:
        is_a_colored_number = has_invisible and isinstance(val, (_text_type, _binary_type))
        if is_a_colored_number:
            raw_val = _strip_invisible(val)
            formatted_val = format(float(raw_val), floatfmt)
            return val.replace(raw_val, formatted_val)
        else:
            return format(float(val), floatfmt)
    else:
        return "{0}".format(val)

在我的代码,我代替以表格形式列出与我这样的内部方法:

from mypkg.tabulate_extensions import _format_extended

tabulate._format = _format_extended

输出现在是任意的。好事是,我现在可以扩展以任何方式我想其他细胞类型的格式(如字典)。

© www.soinside.com 2019 - 2024. All rights reserved.