用于打印的命名元组中的圆形长浮点数

Round long floats in named tuple for printing

我正在打印

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

a 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 位小数,这样这些元组就不会过多地阻塞我的日志吗?

你可以这样做:

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])