首页 > 解决方案 > 检查数字是否不是无并做某事的Pythonic方法

问题描述

这对我来说似乎很基本,但我没有找到一个好的解决方案。

假设像这样的字典:

data = {'values' : [1.3333, None, 2.44444], 'other_values' : [2.3333, 1.2222, None]}

因为内置函数round()显然不能四舍五入None,所以返回错误:

for index in range(0, len(data['values'])):
    result = round(data['values'][index], 2)
    print(result)
    result2 = round(data['other_values'][index], 2)
    print(result2)

一个可能的解决方案是这样的

for index in range(0, len(data['values'])):
    if data['values'][index]:
        result = round(data['values'][index], 2)
        print(result)
    if data['other_values'][index]:
        result2 = round(data['other_values'][index], 2)
        print(result2)

但有没有更蟒蛇的方式?

标签: pythondictionary

解决方案


而不是round(x, 2)你可以做的round(x or 0, 2)


推荐阅读