问题描述
我有一个带有多个值(双精度)的数组,其中许多是重复的.我想返回或打印所有唯一值的列表,以及给定值在数组中出现多少次的计数.我对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-如何从数组中返回重复值的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!