把字典里的值除保持不变剩下的转为浮点型用Python匿名函数写生成新的字典
d = {'a': '1', 'b': '2.0', 'c': '', 'd': '3.14'}
new_d = {key: float(value) if value != '' else value for key, value in d.items()}
print(new_d) # {'a': 1.0, 'b': 2.0, 'c': '', 'd': 3.14}
使用匿名函数:
new_d = {key: (lambda x: float(x) if x != '' else x)(value) for key, value in d.items()}
print(new_d) # {'a': 1.0, 'b': 2.0, 'c': '', 'd': 3.14}
两种方法的输出结果是一样的。
原文地址: https://www.cveoy.top/t/topic/co0t 著作权归作者所有。请勿转载和采集!