Idiomatic Python手记一: average in FP way
方法一:
1 import operator
2
3 def average(*args):
4 return reduce(operator.add, args) / len(args) if args else 0
注释:
- 语句 if []: / if (): / if '' : / if {}: 对于以上空集 逻辑值为 False
- 等同于 if len(list) == 0 : pass 等
方法二:
1 import functools
2
3 def average(*args):
4 acc = functools.partial(reduce, lambda x, y : x + y)
5 # acc = functools.partial(reduce, operator.add)
6 return acc(args) / len(args) if args else 0
注释:
- acc 为初值为lambda 表达式的reduce偏函数