赞
踩
有个业务需求:将列表或字典中的末级值进行转换,而对象的结构不定,可以采用以下的方式进行处理
注意:以下方式只能修改值,而如果需要修改键,则需要使用递归
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]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。