我有一个函数measure_amount()
,如果数量存在,则返回列表中的字典,其中包含来自对象的特定'total'金额。例子:
[{'unit': 'foo', 'total': Decimal('5900.00'), 'type': None}]
当在多个对象上迭代测量时,dict-in-list是可变的,可能有也可能没有'total',也可能是空的。有时函数会返回一个空列表:
[]
我原来的代码是:
for o in objects:
l = o.measure_amount()
# use enumerate to get the index for 'total' if it exists
i = next((index for (index, d) in enumerate(l) if d["total"]), None)
amount = l[i]["total"]
total_amount += amount
return total_amount
当"total"存在于索引中,但当列表为空时抛出错误,因为在索引中为None:
TypeError: list indices must be integers or slices, not NoneType
我可以使用if
语句来检查if i is not None:
作为amount = l[i]["total"]
之前的条件,但我想知道从python的角度-是否有更好的方法来处理这种类型的列表可变性?由于
使用异常,遵循Python的精神:请求原谅,而不是请求许可。
for o in objects:
l = o.measure_amount()
try:
# use enumerate to get the index for 'total' if it exists
i = next((index for (index, d) in enumerate(l) if d["total"]), None)
amount = l[i]["total"]
total_amount += amount
except (KeyError, TypeError):
pass
return total_amount
您可以在total
键上使用dict.get
,并为l
中的每个字典设置默认值Decimal(0)
,然后仅sum
结果:
l = [
{'unit': 'bar', 'type': None},
{'unit': 'foo', 'total': Decimal('5900.00'), 'type': None}
]
sum(d.get('total', Decimal(0)) for d in l)
输出:
Decimal('5900.00')