【问题标题】:Round floats in a nested dictionary recursively递归地在嵌套字典中循环浮点数
【发布时间】:2019-05-08 20:31:58
【问题描述】:

我正在尝试在嵌套字典中对浮点值进行四舍五入,该字典也具有其他值。我看了这个帖子 - Rounding decimals in nested data structures in Python

尝试实现这样的功能:

import collections
import numbers

def formatfloat(x):
    return "%.3g" % float(x)

def pformat(dictionary, function):
    if isinstance(dictionary, dict):
        return type(dictionary)((key, pformat(value)) for key, value in dictionary.items())
    if isinstance(dictionary, collections.Container):
        return type(dictionary)(pformat(value) for value in dictionary)
    if isinstance(dictionary, numbers.Number):
        return formatfunc(dictionary)
    return dictionary

x={'a':[1.05600000001,2.34581736481,[8.1111111112,9.999990111111]], 
   'b':[3.05600000001,4.34581736481,[5.1111111112,6.999990111111]]}

pformat(x, formatfloat)

我收到此错误:

TypeError: pformat() missing 1 required positional argument: 'function'

答案被标记为正确,所以我想知道是否需要更改任何内容。这正是我希望为我的字典实现的。任何帮助表示赞赏!

【问题讨论】:

    标签: python numpy dictionary


    【解决方案1】:

    需要在pformat后面加一个参数:

    之前

    pformat(value))
    

    之后:

    pformat(value, function))
    

    然后将拼写错误:formatfunc改为function

    这是工作代码:

    import collections
    import numbers
    
    def formatfloat(x):
        return "%.3g" % float(x)
    
    def pformat(dictionary, function):
        if isinstance(dictionary, dict):
            return type(dictionary)((key, pformat(value, function)) for key, value in dictionary.items())
        if isinstance(dictionary, collections.Container):
            return type(dictionary)(pformat(value, function) for value in dictionary)
        if isinstance(dictionary, numbers.Number):
            return function(dictionary)
        return dictionary
    
    x={'a':[1.05600000001,2.34581736481,[8.1111111112,9.999990111111]], 
       'b':[3.05600000001,4.34581736481,[5.1111111112,6.999990111111]]}
    
    pformat(x, formatfloat)
    

    结果:

    {'a': ['1.06', '2.35', ['8.11', '10']], 'b': ['3.06', '4.35', ['5.11', '7']]}
    

    【讨论】:

      【解决方案2】:

      这里只是里面的语法错误。

      您在内部调用函数pformat 而不需要参数。你只传递 value 而没有传递 function

      return type(dictionary)((key, pformat(value)) for key, value in dictionary.items())
      

      在最后的if 语句中,您调用未实现的函数formatfunc。可能是错字,需要调用formatfloat函数。

      如果解决这个问题,结果:

      {'a': ['1.06', '2.35', ['8.11', '10']], 'b': ['3.06', '4.35', ['5.11', '7']]}
      

      【讨论】:

        【解决方案3】:

        我写的有点不同:

        x={'a':[1.05600000001,2.34581736481,[8.1111111112,9.999990111111]], 
           'b':[3.05600000001,4.34581736481,[5.1111111112,6.999990111111]]}
        
        
        def recursive_rounding(keys, values):
            to_return = {}
            for key, value in zip(keys, values):
                print key, value
                if isinstance(value, dict):
                    rounded_value = recursive_rounding(value.keys(), value.values())
                elif isinstance(value, (tuple, list)):
                    rounded_value = [round_by_type(x) for x in value]
                else:
                    rounded_value = round_by_type(value)
                print key, value
                to_return[round_by_type(key)] = rounded_value
            return to_return
        
        def round_by_type(to_round):
            if isinstance(to_round, (int, float)):
                return round(to_round, 2)
            elif isinstance(to_round, (list, tuple)):
                return [round_by_type(x) for x in to_round]
            return to_round
        
        recursive_rounding(x.keys(), x.values())
        

        我写得非常快,可以稍微清理一下并进行改进,但只是为了展示你如何从不同的角度来处理它

        输出是:

        # Result: {'a': [1.06, 2.35, [8.11, 10.0]], 'b': [3.06, 4.35, [5.11, 7.0]]} # 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-07-16
          • 2014-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-04
          相关资源
          最近更新 更多