当前位置:   article > 正文

【Py】优雅地遍历字典或列表对象末级值_遍历末级

遍历末级

有个业务需求:将列表或字典中的末级值进行转换,而对象的结构不定,可以采用以下的方式进行处理

注意:以下方式只能修改值,而如果需要修改键,则需要使用递归

import re
from typing import Union
from functools import singledispatch

@singledispatch
def to_decimal128(obj: Union[list, dict]):
    """将列表或字典中的数字转为Decimal128

    Args:
        obj (Union): 列表或字典对象
    """
    if type(obj) in [int, float]:
        obj = decimal128.Decimal128(str(obj))
    return obj


@to_decimal128.register(dict)
def _(d):
    return {str(k): to_decimal128(v) for k, v in d.items()}


@to_decimal128.register(list)
def _(l):
    return [to_decimal128(v) for v in l]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

参考:https://juejin.cn/post/6844903510543171592

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/172036
推荐阅读
相关标签
  

闽ICP备14008679号