通过减少数组创建字典与通过迭代分配每个项目之间的区别 [英] Difference between creating a dictionary by reduce on an array vs by assigning each item on iteration

查看:87
本文介绍了通过减少数组创建字典与通过迭代分配每个项目之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在StackOverflow上遇到了一个问题: Swift-将数组转换为字典 用户想要获取数组中的元素,并希望将其放入字典中,并为每个元素分配0. (关键是玩家,价值是他们的分数) 所以:

I came across a question on StackOverflow: Swift - Convert Array to Dictionary where the user wants to take the elements of an array and wants to put them in a dictionary and assign 0 to each of them. (Key as Players and value as their scores) So:

var playerNames = ["Harry", "Ron", "Hermione"]

成为

var scoreBoard: [String:Int] = [ "Ron":0, "Harry":0, "Hermione":0 ]

此问题有2个答案: 1)在数组上使用reduce

This question got 2 answers: 1) Uses reduce on the array

let scoreboard = playerNames.reduce(into: [String: Int]()) { $0[$1] = 0 }

2)创建一个字典并在数组上迭代以向其中添加每个值键对

2)Creates a dictionary and iterates on array to add each value key pair to it

var dictionary = [String: Int]()
for player in playerNames {
    dictionary[player] = 0
}

我从 https://github.com/nyisztor/swift-algorithms中获取了BenchTimer函数测试这两种解决方法.而且它们似乎都在O(n)中运行.

I took the BenchTimer function from https://github.com/nyisztor/swift-algorithms to test both of these ways of solving. And they both seem to operate in O(n).

我想知道为什么我们比第一个更喜欢第一个,因为写第二个解决方案的人对他们的编码技能有不好的评价.

I was wondering why we would prefer the first one over the other since the person who wrote the second solution got a bad comment about their coding skills.

Apple在较新的版本中不赞成使用某些功能,所以坚持基本知识并创建我们自己的处理方式不是更好吗?

Some functionality gets deprecated by Apple in newer versions so isn't it better to stick with the basics and create our own ways to do things?

谢谢您的回答

推荐答案

今天,IMO,您不应使用其中任何一个.现在,我们有了Dictionary.init(uniqueKeysWithValues:).init(_:uniquingKeysWith:),它们可以更清楚地说明它们的意图,并明确显示极端情况,例如重复的键.

Today, IMO, you shouldn't use either of these. We now have Dictionary.init(uniqueKeysWithValues:) and .init(_:uniquingKeysWith:) which much more clearly state their intent, and make corner cases, such as duplicate keys, explicit.

如果您可以静态证明所有键都是唯一的,则可以使用第一个:

If you statically can prove that all the keys are unique, then you would use the first one:

let scoreboard = Dictionary(uniqueKeysWithValues: playerNames.map { (name: $0, score: 0) })

如果您不能证明密钥是唯一的,则可以使用第二个密钥,这样您就可以明确决定在发生冲突的情况下该怎么做.

If you cannot prove the keys are unique, you'd use the second one, which would allow you to explicitly decide what to do in cases of conflict.

let scoreboard = Dictionary(playerNames.map { (name: $0, score: 0) },
                            uniquingKeysWith: { first, _ in first })

请注意此方法如何使标签明确键名和值.我尚未对该代码进行基准测试,但我希望它在时间上与其他代码非常相似.

Note how this approach allows labels to make clear what the key is and what the value is. I haven't benchmarked this code, but I would expect it to be very similar in terms of time to the others.

这篇关于通过减少数组创建字典与通过迭代分配每个项目之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆