gpt4 book ai didi

iOS swift : How to calculate the sum of each value in a key-pair dictionary and store it in a separate dictionary?

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

目前我有一个定义如下的字典数组:

var dateDouble_ARRAY = [Date : [Double] ]()

dateDouble_ARRAY = [2017-08-06 07:00:00 +0000: [11.880000000000001, 3.0],
2013-08-08 07:00:00 +0000: [5.0],
2016-08-01 07:00:00 +0000: [6.0],
2017-08-09 07:00:00 +0000: [6.0],
2013-08-02 07:00:00 +0000: [5.0],
2012-08-03 07:00:00 +0000: [6.5499999999999998],
2015-08-10 07:00:00 +0000: [2.0] ]

我想做的是获取所有日期的年份并将其存储在 [String: Double] 键值字典中,其中与年份键配对的值是 <该特定年所有值的强>总和。

例如,在上面的代码中,以下是所需的输出:

var yearDouble_ARRAY = [ "2012": 6.5499999999999998, 
"2013": 10.0,
"2015": 2.0,
"2016": 6.0,
"2017: 20.880000000000001]

注意:对于“2017”,20.880000000000001 是从[ (11.880000000000001 + 3.0) + 6.0] 获得的。

怎样才能达到预期的效果?

谢谢!

到目前为止我尝试了什么

var stringDates = [String: Int]()

for (index, date) in dateDouble_ARRAY.enumerated()
{
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"

let yearOnly = formatter.string(from: date.key)

stringDates[yearOnly] = index
}

let yearOnly_ARRAY = stringDates.keys.sorted()

但是,我只能存储不重复的年份,我不确定如何求和与年份相关的值。

最佳答案

您的代码只缺少当前 double 的总和:

let datesDoubles = [
Date(): [11.880000000000001, 3.0],
Date(timeIntervalSinceNow: 3600 * 24 * 60 * -1 ): [6.0],
Date(timeIntervalSinceNow: 3600 * 24 * 365 * -1): [5.0],
Date(timeIntervalSinceNow: 3600 * 24 * 365 * -1 * 2): [6.0],
Date(timeIntervalSinceNow: 3600 * 24 * 365 * -1 * 4): [5.0],
Date(timeIntervalSinceNow: 3600 * 24 * 365 * -1 * 5): [6.5499999999999998],
Date(timeIntervalSinceNow: 3600 * 24 * 365 * -1 * 6): [2.0]
]

var stringDates = [String : Double]()
let formatter: DateFormatter = {
$0.dateFormat = "yyyy"
return $0
}(DateFormatter())

for dateDouble in datesDoubles {
let yearOnly = formatter.string(from: dateDouble.key)

if let valueForDate = stringDates[yearOnly] {
stringDates[yearOnly] = valueForDate + dateDouble.value.reduce(0,+)
} else {
stringDates[yearOnly] = dateDouble.value.reduce(0,+)
}
}

print(stringDates)

关于iOS swift : How to calculate the sum of each value in a key-pair dictionary and store it in a separate dictionary?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45656228/

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