四舍五入的Python列表项,每个项都有不同的小数位

2024-04-27 03:54:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python3.6.4

我有一个类,在其中我计算了一堆属性。我必须把所有这些四舍五入到不同的小数位,有些小数位可以是零。你知道吗

示例:

假设我有以下属性,值,小数位

a, 1.155 , 0
b, 1.123 , 2
c, None  , 1
...

结果我需要的是

a= 1.2
b= 1.23
c= None
...

琐碎的解决方案

我对每一个属性都像

if attribute is not None:
    attribute = round(attribute, decimal_places)

但我有太多的属性。你知道吗

我尝试的:

我列了一个元组列表(属性,小数点)。像这样:

attributes_decimal_places =  [
            (self.a, 0),
            (self.b, 2),
            (self.c, 1),
]

在这个列表中,我可以运行下面的命令,它给出了正确的舍入值,但是我不能将这个resultvalues保存在属性中

solution = [round(x[0], x[1]) if isinstance(x[0], float) else x[0] for x in attributes_decimal_points]

问题:

如何将舍入值放入属性而不是列表中?你知道吗

解决方案:

感谢所有回答的人。一个适合我的解决方案:

    attributes_decimal_points = [
        (self.a, "a", 1),
        (self.b, "b", 2),
        (self.c, "c", 3)
    ]

    for attribute in attributes_decimal_points:
        if attribute[0] is None:
            continue
        else:
            setattr(self, attribute[1], round(attribute[0], attribute[2])) 

Tags: selfnone列表if属性isattribute解决方案
1条回答
网友
1楼 · 发布于 2024-04-27 03:54:12

您可以使用字典:

    solution = {}
    for x in attributes_decimal_points:
        if isinstance(x[0], float):
            solution.update({x[0]: round(x[0], x[1])})
        else:
            solution.update({x[0]: x[1]})

这样就可以通过属性的名称来获取属性。你知道吗

相关问题 更多 >