字典定義為
var weekActualPowerZoneTimes: [String:[Int]]()
weekActualPowerZoneTimes:
[
"Ride" : [1, 1, 1, 1, 1, 1, 1, 1],
"Run" : [1, 1, 1, 1, 1, 1, 1, 1],
"Swim" : [1, 1, 1, 1, 1, 1, 1, 1],
"Other" : [1, 1, 1, 1, 1, 1, 1, 1]
]
目標:將這些陣列組合成一個。也就是說,我正在尋找這個輸出
[4, 4, 4, 4, 4, 4, 4, 4]
要求和的陣列在技術上應該具有相同的大小,但它們可能不取決于用戶偏好。(有些用戶可能會選擇有 7 個 Power Zones,有些用戶可能會在未來使用 5 個)
我目前能夠使用它對 2 個陣列求和
let arrayResult:[Int] = zip(array1,array2).map( )
但是在如何對字典中可能的任意數量的陣列求和(例如:用戶可能只進行跑步/游泳或跑步/游泳/騎行或其他/游泳)上陷入困境。
更新:我試過這個,它有效,但前提是我定義了初始的“組合”陣列
var combined = [0,0,0,0,0,0,0,0]
let aa =
[
"Ride" : [1, 1, 1, 1, 1, 1, 1, 1],
"Run" : [2, 1, 1, 1, 1, 1, 1, 1],
"Swim" : [3, 1, 1, 1, 1, 1, 1, 1],
"Other" : [4, 1, 1, 1, 1, 1, 1, 1]
]
for (index,values) in aa.values.enumerated(){
print(index, values)
combined = zip(combined,values).map( )
print("\(combined)") // [10, 4, 4, 4, 4, 4, 4, 4]
}
但如果初始combined陣列定義為[] ,則會導致
var combined = [Int]()
uj5u.com熱心網友回復:
我在 reddit 上發現這種壓縮變體適用于不同長度的陣列
func add(a: [Int], b: [Int]) -> [Int] {
zip(a, b).map( ) (a.count < b.count ? b[a.count ..< b.count] : a[b.count ..< a.count])
}
這樣我們就可以遍歷字典的值
var combined = [Int]()
weekActualPowerZoneTimes.values.forEach {
combined = add(a: combined, b: $0)
}
forEach對值使用回圈意味著我們可以擁有任意數量的值,并且該add函式意味著值陣列可以具有不同的長度
uj5u.com熱心網友回復:
在基本回圈中,我的邏輯變得清晰。冗長但仍然。
var combine = [Int]()
for (_, powerzone) in weekActualPowerZoneTimes {
for i in powerzone.indices {
if combine.endIndex > i {
combine[i] = array[i]
} else {
combine[i] = array[i]
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321553.html
下一篇:從另一個陣列的內容中過濾陣列
