Mak*_*lle 4 functional-programming swift
我正在尝试将元素与集合中的下一个元素进行比较.
例如 :
let array: [(Double, String)]= [(2.3, "ok"),
(1.4, "ok"),
(5.1, "notOk")]
Run Code Online (Sandbox Code Playgroud)
我需要一个返回的数组,它将汇总字符串相同的元素.所以我的结果将是:
new array = [(3.7, "ok"), (5.1, "notOk")]
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我需要做它的功能.我试图在地图中获取下一个元素,但无法找到.
像这样的东西(这只是为了逻辑,这段代码不起作用.
let newArray = array.map {(element, nextElement) in
if element.1 == nextElement.1 {
return element.0 + nextElement.0
}
}
Run Code Online (Sandbox Code Playgroud)
以更实用的方式:
let array: [(Double, String)]= [(2.3, "ok"),
(1.4, "ok"),
(5.1, "notOk")]
let keys = Set(array.map{$0.1}) // find unique keys
let result = keys.map { key -> (Double, String) in
let sum = array.filter {$0.1 == key} // find all entries with the current key
.map {$0.0} // map them to their values
.reduce(0, +) // sum the values
return (sum, key)
}
print(result)
Run Code Online (Sandbox Code Playgroud)
输出:
[(5.0999999999999996,"notOk"),(3.6999999999999997,"ok")]
或者(由@dfri建议):
let keys = Set(array.map{$0.1}) // find unique keys
let result = keys.map { key -> (Double, String) in
let sum = array.reduce(0) { $0 + ($1.1 == key ? $1.0 : 0) }
return (sum, key)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1132 次 |
| 最近记录: |