在 Ruby 中,我习惯使用 Enumerable#inject 来遍历列表或其他结构,并得出有关其的一些结论。例如,
[1,3,5,7].inject(true) {|allOdd, n| allOdd && n % 2 == 1}
如何确定数组中的每个元素都是奇数?在Python中,实现同样功能的适当方法是什么?
在 Ruby 中,我习惯使用 Enumerable#inject 来遍历列表或其他结构,并得出有关其的一些结论。例如,
[1,3,5,7].inject(true) {|allOdd, n| allOdd && n % 2 == 1}
如何确定数组中的每个元素都是奇数?在Python中,实现同样功能的适当方法是什么?
reduce(lambda x, y: x and y % == 1, [1, 3, 5])
我认为你可能希望使用all
,它比inject
更具体。而reduce
则是Python中等价于inject
的函数。
all(n % 2 == 1 for n in [1, 3, 5, 7])
reduce()
已经移动到 Python 3 的functools.reduce()
。 - 200_success