gpt4 book ai didi

Swift3循环字典增加值

转载 作者:行者123 更新时间:2023-11-30 12:28:38 25 4
gpt4 key购买 nike

我是编程新手,我只是在 Playground 上玩耍,我试图在字典中循环进行一些计算并将它们添加到新字典中,但是,我只能添加一个字典值。我不知道为什么。能再告诉我并指出要点吗?

    var name:String?

var popDict: [String: Array<Double>]?
var FinalDict: [String: Array<Double>]?
var mean: Double?
var elementSideArr: Array<Double>?

var nameArray = ["Olivia": [1,2,2,2,1,2,1,0.0001,0,1,2], "Amber": [52,52,65,66,57,63,62,0.0001,0,0,0]]

var doubleArr = [Double]()

for (key, value) in nameArray{

let thisValue = value
let arrayS = thisValue.prefix(7)
let slice = arrayS[0...6]
let popSideArr = Array(slice)
let average: Double = (popSideArr as NSArray).value(forKeyPath: "@avg.self") as! Double

mean = average
let thatValue = value
let arraySS = thatValue.suffix(3)
let sslice = arraySS[8...10]
elementSideArr = Array(sslice)


elementSideArr?.insert(average, at: 0)


let dict = ["\(key)": elementSideArr!]

for (key,value) in dict{

popDict = dict

}
}
print(popDict!)

["Olivia": [1.5714285714285714, 0.0, 1.0, 2.0]]//这是唯一的输出,但应该是 2 项。

最佳答案

问题出在你的内部for循环中,你正在将整个新字典初始化为popDict,而且如果你的字典只有单个键和值对,你也不需要for循环。

替换代码行:

let dict = ["\(key)":  elementSideArr!]
for (key,value) in dict{
popDict = dict
}

与:

popDict["\(key)"] = elementSideArr!

注意:无需将 swift 数组转换为 NSArray 来计算平均值,您只需使用 reduce 即可获取总计,然后除以总计与数组计数。

let array = popSideArr as? [Int] ?? []
let res = Double(array.reduce(0, +)) / Double(popSideArr.count)

关于Swift3循环字典增加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43861500/

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