我有一个包含 Double
数组的数组,如屏幕截图所示:
我的目标是获取每个数组的 Double
元素相乘的总和。这意味着,我想乘以每个数组的所有元素,然后在我的例子中,我将有 3 个值,所以我得到它们的总和。
我想使用reduce
, flatMap
吗?或任何优雅的解决方案。
我尝试了什么?
totalCombinations.reduce(0.0) { $0 + ($1[0]*$1[1]*$1[2]) }
但这只有在我知道包含 double 组的大小时才有效。
最佳答案
给定这些值
let lists: [[Double]] = [[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]
让我们来看看几种可能的方法
解决方案#1
let sum = lists.reduce(0) { $0 + $1.reduce(1, combine: *) }
解决方案#2
如果你定义这个扩展
extension SequenceType where Generator.Element == Double {
var product : Double { return reduce(1.0, combine: *) }
}
然后你就可以写了
let sum = lists.reduce(0) { $0 + $1.product }
解决方案#3
使用上面定义的扩展你也可以写
let sum = lists.map { $0.product }.reduce(0, combine:+)
解决方案 #4
如果我们定义这两个后缀运算符
postfix operator +>{}
postfix func +>(values:[Double]) -> Double {
return values.reduce(0, combine: +)
}
postfix operator *>{}
postfix func *>(values:[Double]) -> Double {
return values.reduce(1, combine: *)
}
我们可以写
lists.map(*>)+>
关于ios - 在 Swift 中使用嵌套 reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38634324/