Python中inject()的等效方法是什么?
在Ruby中,我习惯使用Enumerable#inject这个方法来遍历一个列表或其他结构,并得出一些结论。例如,
[1,3,5,7].inject(true) {|allOdd, n| allOdd && n % 2 == 1}
我可以用它来判断数组中的每个元素是否都是奇数。那么在Python中,应该用什么方法来实现同样的功能呢?
3 个回答
4
我觉得你可能想用 all
,因为它比 inject
更简单一些。不过,reduce
在 Python 里是和 inject
相对应的。
all(n % 2 == 1 for n in [1, 3, 5, 7])
8
听起来像是Python中的reduce
函数,或者Haskell中的fold(r|l)
。
reduce(lambda x, y: x and y % == 1, [1, 3, 5])