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

标签 python logging rounding namedtuple

我正在打印

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/

相关文章:

python - 调用函数时如何传递变量关键字参数

java - java.math.RoundingMode 是如何工作的?

Android - 四舍五入到小数点后两位

python - Pandas Shift 将整数转换为 float 和整数

c# - 在外部库中使用 TraceWriter 进行 Azure 函数日志记录

python - "AttributeError: ' 模块 ' object has no attribute ' __getstate__ ' "在我使用 easy_install 时出现

python - 计算字母字符串的长度并转化为真/假陈述

python - Python urllib 的意外行为

python - 如何在Python模块初始化时启用日志记录?

php - Yii 不明白如何记录消息