我正在打印
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])
有什么办法可以将列表内外的浮点数自动舍入为两位小数,以便这些元组不会过多阻塞我的日志?
答案 0 :(得分: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])