python - 检查数字是否不是无并做某事的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)
但有没有更蟒蛇的方式?
解决方案
而不是round(x, 2)
你可以做的round(x or 0, 2)
。
推荐阅读
- docker - `docker logs` vs `docker container logs`
- asp.net-mvc - @: in a foreach loop doesn't work when it's between tags?
- apache - Directus api 和应用程序与前端在同一台服务器上
- java - call procedure with out parameters in hibernate3
- react-native - React Native - Vector icons in Navigation bar
- sapui5 - Column sum of UI5 table
- python - 是否可以在 python 中创建语句?
- python - TensorFlow Probability MCMC with Bernoulli distribution
- java - 简单的正则表达式模式匹配
- google-tag-manager - 确保正确设置 DataLayer