我有字典,比方说
let gamePrices = [
"Shooter": [40,60,80],
"RTS": [15,35,55]
"RPG": [5,40,70]
]
avgGamePrices(dictionary: [String: Int]) -> Double {
var total = 0;
for int in dictionary {
total += int
}
(我想,这里使用int是错误的),而且我不了解如何获取每种流派的平均价格和全部(全部9个值)平均价格。我什至不知道如何在此处求和,我应该如何在for循环中“提及”字典的整数或字符串?对于默认数组我会使用
for number in numbers {
total += number
}
let numbersTotal = Int(numbers.count);
let average = total/numbersTotal;
return (Double(average);
要获取所有价格的平均值,您需要首先从字典中获取所有价格,然后才能计算平均值。它与计算平均值的平均值不同:
let gamePrices = [
"Shooter": [40,60,80],
"RTS": [15,35,55],
"RPG": [5,40,70]]
let allPrices = gamePrices.flatMap(\.value)
let sum = allPrices.reduce(.zero, +)
let average = Double(sum) / Double(allPrices.count) // 44.44444444444444
要获得每种类型的最高价格:
let maxPrices: [(genre: String, maxPrice: Int)] = gamePrices.map { ($0, $1.max() ?? .zero)} // [(genre "Shooter", maxPrice 80), (genre "RTS", maxPrice 55), (genre "RPG", maxPrice 70)]
for (genre, max) in maxPrices {
print("Genre:", genre, "Max price:", max)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句