我正试图找到一种方法,在不使用"repeat"或Kotlin上的任何循环的情况下获得列表或数组的乘积,但经过一些研究,我找不到任何类似的方法.
在Python中,类似这样的内容是:
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
output: 720
我正试图找到一种方法,在不使用"repeat"或Kotlin上的任何循环的情况下获得列表或数组的乘积,但经过一些研究,我找不到任何类似的方法.
在Python中,类似这样的内容是:
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
output: 720
You can use reduce
in Kotlin.
从文档中:
Accumulates value starting with the first element and applying operation from left to right to current accumulator value and each element.
val list = listOf<Int>(1, 2, 3, 4, 5, 6)
val array = intArrayOf(1, 2, 3, 4, 5, 6)
list.reduce { acc, i -> acc * i } // returns 720
array.reduce { acc, i -> acc * i } // returns 720