根据另一个数组的顺序对数组进行有效排序 [英] efficient sorting of an array based on another array's order

查看:595
本文介绍了根据另一个数组的顺序对数组进行有效排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个:

struct Pet {
    let name: String
}

let pets = [Pet(name: "Z"), Pet(name: "F"), Pet(name: "A"), Pet(name: "E")]
let petNames = ["E", "F", "Z", "A"]

我的预期输出是:

[Pet(name: "E"), Pet(name: "F"), Pet(name: "Z"), Pet(name: "A")]

如何按照petNames'的顺序有效地对pets进行排序?

How do I sort pets efficiently by following petNames' order?

我当前的方法似乎效率很低:

My current method appears to be horribly inefficient:

var sortedPets = [Pet]()
for n in petNames {
    sortedPets.append(pets.first(where: { return $0.name == n })!)
}

我可以使用任何功能方法吗?

Any functional approach that I could use?

推荐答案

效率不高,但可以从功能上解决问题:

Not efficient, but it solves the problem functionally:

let pets2 = pets.sorted{petNames.index(of:$0.name)! < petNames.index(of:$1.name)!}

现在我们知道要执行的操作了,因为字典查找速度很快,所以操作更加精细,但效率更高:

Now that we know what we're after, this is more elaborate but much more efficient, because dictionary lookup is fast:

var d = [String:Int]()
zip(petNames, 0..<petNames.count).forEach { d[$0.0] = $0.1 }
let pets2 = pets.sorted{d[$0.name]! < d[$1.name]!}

这篇关于根据另一个数组的顺序对数组进行有效排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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