gpt4 book ai didi

arrays - 如何从 Swift3 中的数组按日期/月份/年份计算平均值

转载 作者:行者123 更新时间:2023-12-05 04:10:01 28 4
gpt4 key购买 nike

我有一个字典数组。

字典类似于 ["date":"2017-07-03T10:12:00", "amount":2.1]

编辑

比方说,我有以下数组。

let dic1 = ["date":"2017-07-03T10:12:00", "amount":2.0]
let dic2 = ["date":"2017-07-03T11:15:03", "amount":4.0]
let dic3 = ["date":"2017-07-03T17:05:04", "amount":1.0]
let dic4 = ["date":"2017-07-04T09:05:03", "amount":3.0]
let dic5 = ["date":"2017-07-04T12:01:22", "amount":5.0]
let dic6 = ["date":"2017-07-04T19:01:01", "amount":2.0]
let array = [dic1, dic2, dic3, dic4, dic5, dic6]

现在我正在尝试从 Array 计算以下结果。

"date":"2017-07-03", "average":3.5
"date":"2017-07-04", "average":5.0
"date":"2017-07", "average":2.82..
"date":"2017", "average":2.82..

我可以用下面的代码得到所有数据的平均值,但我现在卡住了。

let average = array.flatMap({ $0["amount"] as? Double }).reduce(0, +) / Double(array.count)

最佳答案

建议使用包含日期格式化程序的自定义结构将 ISO8601 字符串转换为 Date

struct Item {
let date : Date
let amount : Double

static let dateFormatter : ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withFullDate, .withTime, .withColonSeparatorInTime]
return formatter
}()

init(date: String, amount: Double) {
self.date = Item.dateFormatter.date(from: date)!
self.amount = amount
}
}

填充数组

let items = [Item(date : "2017-07-03T10:12:00", amount :2.0),
Item(date : "2017-07-03T11:15:03", amount :4.0),
Item(date : "2017-07-03T17:05:04", amount :1.0),
Item(date : "2017-07-04T09:05:03", amount :3.0),
Item(date : "2017-07-04T12:01:22", amount :5.0),
Item(date : "2017-07-04T19:01:01", amount :2.0)]

创建一个函数,将数组和特定的日期组件作为参数

func average(of items: [Item], matching components: DateComponents) -> Double
{
let filteredDates = items.filter { Calendar.current.date($0.date, matchesComponents: components) }
return filteredDates.map{ $0.amount }.reduce(0.0, +) / Double(filteredDates.count)
}

现在按日期组件过滤项目并返回平均值

average(of: items, matching: DateComponents(year: 2017, month: 7, day: 3))
average(of: items, matching: DateComponents(year: 2017, month: 7, day: 4))
average(of: items, matching: DateComponents(year: 2017, month: 7))
average(of: items, matching: DateComponents(year: 2017))

关于arrays - 如何从 Swift3 中的数组按日期/月份/年份计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45060493/

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