问题描述
我有一个包含多个值(双倍)的数组,其中许多是重复的.我想返回或打印所有唯一值的列表,以及给定值在数组中出现的次数.我对 Swift 还很陌生,我尝试了几种不同的方法,但我不确定实现此目的的最佳方法.
I have an array with multiple values (Doubles), many of which are duplicates. I'd like to return or print a list of all unique values, along with a count of how many times a given value appears in the array. I'm pretty new to Swift and I've tried a couple of different things but I'm unsure of the best way to accomplish this.
是这样的:[65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5]
Something like this:[65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5]
会打印(例如):3 个在 65.0,2 个在 55.5,2 个在 30.25,1 个在 27.5."
Would print (for example):"3 at 65.0, 2 at 55.5, 2 at 30.25, 1 at 27.5."
我真正关心的不是输出,而是实现此目的的方法.
I'm not really concerned about the output as much as the method to accomplish this.
谢谢!
推荐答案
您可以枚举数组并将值添加到字典中.
You can enumerate through the array and add the values to the dictionary.
var array: [CGFloat] = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5]
var dictionary = [CGFloat: Int]()
for item in array {
dictionary[item] = dictionary[item] ?? 0 + 1
}
print(dictionary)
或者你可以在数组上做 foreach:
or you can do foreach on array:
array.forEach { (item) in
dictionary[item] = dictionary[item] ?? 0 + 1
}
print(dictionary)
或者正如@rmaddy 所说:
or as @rmaddy said:
var set: NSCountedSet = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5]
var dictionary = [Float: Int]()
set.forEach { (item) in
dictionary[item as! Float] = set.count(for: item)
}
print(dictionary)
这篇关于Swift 4 - 如何从数组中返回重复值的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!