【问题标题】:How to find an average for dictionary in Swift?如何在 Swift 中找到字典的平均值?
【发布时间】:2020-10-05 15:56:08
【问题描述】:

我有一本字典,比如说

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);

【问题讨论】:

  • 你能不能少点射手对 RTS 的重视?
  • 恐怕不行,我在这里写了自己的新代码。但首先我需要完成我的任务,并且字符串的整数数量相同(如我的示例)

标签: arrays swift dictionary


【解决方案1】:

要获取所有价格的平均值,您需要先从字典中获取所有价格,然后才能计算平均值。与计算平均值的平均值不同:

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)
}

【讨论】:

  • 谢谢,maxPrices 确实有效,但它会在控制台打印很多“垃圾”,没有地图、?? 和 .zero 有没有更简单的方法?
  • 如果您确定价格数组不为空,您可以强制展开其值或将结果保留为可选
  • 好的,那么你能解释一下它是什么以及它是如何工作的“gamePrices.map { ($0, $1.max() ?? .zero)}”。我从来没有使用过类似的东西,有 ??、.zero 和 $ 符号,所以我真的不明白这是什么
  • 好的 $0 是元组的第一个元素,$1 是第二个。字典是一个集合,其元素是定义为public typealias Element = (key: Key, value: Value) 的键值对。所以我正在映射每个键值对。 $0 是键,而 $1 是值(这是一个集合)。 max 是集合的一个方法,它返回最大值,如果集合为空,则返回 nil
  • @JoakimDanielson 我同意这不是问题的一部分,但我会在不到 30 秒的时间内将其添加到帖子中。考虑到我面前已经有了代码,我决定也将其发布。至少 OP 在尝试解决原始问题时表现出了一些努力。
【解决方案2】:

如果您搜索总 AVG,则如下所示:

func avgGamePrices(dictionary: [String: [Int]]) -> Double {
var total = 0;
var countElem = 0

for obj in dictionary {
    countElem += obj.value.count
    for v in obj.value {
        total += v
    }
}

return Double(total / countElem)

}

调用:

avgGamePrices(dictionary: gamePrices)

否则对于每个键:

func avg(for key: String, dictionary: [String: [Int]]) -> Double {
var total = 0;
let countElem = (dictionary[key] ?? []).count

for v in (dictionary[key] ?? []) {
    total += v
}

return Double(total / countElem)

}

您可以通过这种方式调用(像参数一样传递字典的单个键):

avg(for: "RTS", dictionary: gamePrices)

【讨论】:

  • 应该可以,谢谢,但在这种情况下,我如何计算 int 和 total avg 的 avg?
  • 我真的不明白如何调用这个函数...``` print(avgGamePrices(dictionary : gamePrices)); ```这似乎不对
  • 谢谢,这是可行的,不过我已经在没有 func 的情况下使用 for 循环和打印(我在其中进行了这样的计算“total / Double(price.count)”)。我要做的最后一件事 - 获得每种类型的最高价格。如果不难,请告诉我错误在哪里?我认为,它可以用单行代码来完成。 let maxPrice = gamePrices.max {a,b in a.value
  • 请注意,先进行整数除法,然后将其转换为Double有点没有意义,此时精度已经丢失,因此最好先将值转换为Double再进行除法。
  • 你应该使用Dictionary Key-based subscript with default value,它返回一个非可选值dictionary[key, default: []]
猜你喜欢
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 1970-01-01
  • 2019-03-14
  • 1970-01-01
  • 2021-10-12
相关资源
最近更新 更多