【问题标题】:Round long floats in named tuple for printing [duplicate]用于打印的命名元组中的圆形长浮点数[重复]
【发布时间】:2018-11-23 13:12:08
【问题描述】:

我正在打印

print(f"my named tuple: {my_tuple}")

一个namedtuple,包含整数、浮点数、字符串和每个列表:

MyTuple = namedtuple(
    "MyTuple",
    ["my_int", "my_float", "my_str", "my_float_list"],
)
my_tuple = MyTuple(42, 0.712309841231, "hello world", [1.234871231231,5.98712309812,3.623412312e-2])

输出类似于

MyTuple = (my_int=42, my_float=0.712309841231, my_str="hello world", my_float_list=[1.234871231231,5.98712309812,3.623412312e-2])

有什么方法可以自动将列表内外的浮点数舍入到 2 个十进制数字,这样这些元组就不会过多地阻塞我的日志?

【问题讨论】:

    标签: python logging rounding namedtuple


    【解决方案1】:

    你可以这样做:

    my_tuple = (42, 0.712309841231, "hello world", [1.234871231231,5.98712309812,3.623412312e-2, 'cc', 12])
    l = []
    for i in my_tuple:
        if isinstance(i, float):
            i = format(i, ".2f")
            l.append(float(i))
        elif isinstance(i, list):
            i = [float(format(el, ".2f")) if isinstance(el, float) else el for el in i]
            l.append(i)
        else:
            l.append(i)
    
    from collections import namedtuple
    MyTuple = namedtuple("MyTuple",["my_int", "my_float", "my_str", "my_float_list"],)
    my_tuple = MyTuple(*l)
    print (my_tuple)
    

    输出:

    MyTuple(my_int=42, my_float=0.71, my_str='hello world', my_float_list=[1.23, 5.99, 0.04, 'cc', 12])
    

    【讨论】:

    • 请注意,列表并不都包含我的问题中提到的浮点数。有些包含整数或字符串。
    • @Casimir 我已经更新了答案。请检查是否正常
    • 有没有办法在打印输出中保留关键字(my_int=..., my_float=...)?我尝试按照linked duplicate 中的建议重新定义__str__ 方法,然后最后将其反馈给构造函数,即def __str__(self): {... your code ...} return str(MyTuple(*l)),但这会遇到最大递归错误。
    • 你可以在for loop后面加my_tuple = MyTuple(*l)试试
    • 是的,我试过了。
    猜你喜欢
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多