gpt4 book ai didi

kotlin - Kotlin 中列表或数组的乘积

转载 作者:IT老高 更新时间:2023-10-28 13:46:36 26 4
gpt4 key购买 nike

我正在尝试找到一种方法来获取列表或数组的乘积,而无需在 Kotlin 上使用“重复”或任何循环,但经过一些研究,我找不到类似的东西。

在 Python 中这样的东西是:

>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
output: 720

最佳答案

您可以使用 reduce在 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

关于kotlin - Kotlin 中列表或数组的乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45888370/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com