gpt4 book ai didi

python - 命名元组中的圆形长 float 用于打印

转载 作者:行者123 更新时间:2023-12-01 08:42:26 24 4
gpt4 key购买 nike

我正在打印

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

一个namedtuple包含整数、 float 、字符串和列表:

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

有什么方法可以自动将列表内和外部的 float 四舍五入为小数点后两位,这样这些元组就不会过多地堵塞我的日志?

最佳答案

你可以这样做:

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

关于python - 命名元组中的圆形长 float 用于打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53447385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com