【发布时间】:2017-09-04 11:46:09
【问题描述】:
您好,我有一本字典,我只想像这样删除重复值(使用它们的键):
var myDict : [Int:String] = [1:"test1", 2:"test2", 3:"test1", 4:"test4"]
期望的输出:
[1: "test1", 2: "test2", 4: "test4"]
【问题讨论】:
标签: ios dictionary swift3
您好,我有一本字典,我只想像这样删除重复值(使用它们的键):
var myDict : [Int:String] = [1:"test1", 2:"test2", 3:"test1", 4:"test4"]
期望的输出:
[1: "test1", 2: "test2", 4: "test4"]
【问题讨论】:
标签: ios dictionary swift3
您可以使用此代码
let newDict = myDict.keys.sorted().reduce([Int:String]()) { (res, key) -> [Int:String] in
guard let value = myDict[key], !res.values.contains(value) else { return res }
var res = res
res[key] = value
return res
}
请记住,字典没有排序,所以输出可能是这样的
[2: "test2", 4: "test4", 1: "test1"]
请参考 @Duncan 提供的answer 以获得更快的解决方案。
【讨论】:
var myDict: [Int:String] = [1:"test1", 2:"test2", 3:"test1", 4:"test4"]
var result: [Int:String] = [:]
for (key, value) in myDict {
if !result.values.contains(value) {
result[key] = value
}
}
print(result)
【讨论】:
这是另一种方法
var myDict : [Int:String] = [1:"test1", 2:"test1", 3:"test1", 4:"test4", 5:"test4"]
var newDict:[Int: String] = [:]
for (key, value) in myDict {
print(key, value)
let keys = myDict.filter {
return $0.1.contains(value)
}.map {
return $0.0
}
if keys.first == key {
newDict[key] = value
}
}
print(newDict)
【讨论】:
在我看来,所有其他答案都将具有 O(n^2) 性能。
这是一个应该在 O(n) 时间内运行的解决方案:
var sourceDict = [1:"test1", 2:"test2", 3:"test1", 4:"test4"]
var uniqueValues = Set<String>()
var resultDict = [Int:String](minimumCapacity: sourceDict.count)
//The reserveCapacity() function doesn't exist for Dictionaries, as pointed
//out by Hamish in the comments. See the initializer with minimumCapacity,
//above. That's the way you have to set up a dictionary with an initial capacity.
//resultDict.reserveCapacity(sourceDict.count)
for (key, value) in sourceDict {
if !uniqueValues.contains(value) {
uniqueValues.insert(value)
resultDict[key] = value
}
}
对于小型字典,差异是微不足道的,但如果你有一个包含数百(或数千)键/值对的字典,那么 n^2 算法的性能开始变得真的很差。
【讨论】:
Dictionary 没有 reserveCapacity(_:) 方法(尽管它确实应该)——您可能打算改用 init(minimumCapacity:) 初始化程序。