我看过StackOverflow,但是没有找到任何地方可以讨论在字典中取特定Int或Double的平均值。这是我创建的自定义词典:
var allInformationByDate = [
"1989-06-20": DayData(sales: 0, doorsKnocked: 0, milesWalked: 0.00, hoursWorked: 0.00),
"2016-06-22": DayData(sales: 2, doorsKnocked: 30, milesWalked: 2.00, hoursWorked: 3.00),
"2016-08-16": DayData(sales: 4, doorsKnocked: 30, milesWalked: 10.00, hoursWorked: 0.00)
]
所以我希望得到每一个的平均值。例如:
var avgSales = average(sales) = 2
var avgDoors = average(doorsKnocked) = 20
var avgMiles = average(milesWalked) = 4.0
var avgHours = average(hoursWorked) = 1.0
有人知道语法吗?谢谢你的帮忙!
最佳答案
var allInformationByDate = [
"1989-06-20": DayData(sales: 0, doorsKnocked: 0, milesWalked: 0.00, hoursWorked: 0.00),
"2016-06-22": DayData(sales: 2, doorsKnocked: 30, milesWalked: 2.00, hoursWorked: 3.00),
"2016-08-16": DayData(sales: 4, doorsKnocked: 30, milesWalked: 10.00, hoursWorked: 0.00)
]
override func viewDidLoad() {
super.viewDidLoad()
var avgSales:Double! = 0.0
var avgDoorsKnocked:Double! = 0.0
var avgMilesWalked:Double! = 0.0
var avgHoursWorked:Double! = 0.0
let totalDays = Double(allInformationByDate.count)
for (date, dayData) in allInformationByDate {
print("date: \(date)")
avgSales = avgSales + Double(dayData.sales)
avgDoorsKnocked = avgDoorsKnocked + Double(dayData.doorsKnocked)
avgMilesWalked = avgMilesWalked + dayData.milesWalked
avgHoursWorked = avgHoursWorked + dayData.hoursWorked
}
avgSales = avgSales/totalDays
avgDoorsKnocked = avgDoorsKnocked/totalDays
avgMilesWalked = avgMilesWalked/totalDays
avgHoursWorked = avgHoursWorked/totalDays
print("\(avgSales),\(avgDoorsKnocked),\(avgMilesWalked), \(avgHoursWorked)")
}
关于swift - Swift-取字典元素的平均值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39652357/