我有一个具有多个值(双精度)的数组,其中许多是重复的。我想返回或打印所有唯一值的列表,以及给定值在数组中出现多少次的计数。我对Swift来说还很陌生,我尝试了几种不同的方法,但是我不确定实现此目的的最佳方法。
像这样的内容:[65.0、65.0、65.0、55.5、55.5、30.25、30.25、27.5]
将打印(例如):“ 3 at 65.0、2 at 55.5、2 at 30.25、1 at 27.5”。
我不太关心输出,而不是实现此目的的方法。
谢谢!
正如@rmaddy已经评论的那样,您可以按以下方式使用Foundation NSCountedSet:
import Foundation // or iOS UIKit or macOS Cocoa
let values = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5]
let countedSet = NSCountedSet(array: values)
print(countedSet.count(for: 65.0)) // 3
for value in countedSet {
print("Element:", value, "count:", countedSet.count(for: value))
}
Run Code Online (Sandbox Code Playgroud)
Xcode 11•Swift 5.1
您还可以扩展NSCountedSet以返回元组数组或字典:
extension NSCountedSet {
var occurences: [(object: Any, count: Int)] { map { ($0, count(for: $0))} }
var dictionary: [AnyHashable: Int] {
reduce(into: [:]) {
guard let key = $1 as? AnyHashable else { return }
$0[key] = count(for: key)
}
}
}
Run Code Online (Sandbox Code Playgroud)
let values = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5]
let countedSet = NSCountedSet(array: values)
for (key, value) in countedSet.dictionary {
print("Element:", key, "count:", value)
}
Run Code Online (Sandbox Code Playgroud)
对于Swift本机解决方案,我们可以将Sequence其元素的约束扩展到Hashable:
extension Sequence where Element: Hashable {
var frequency: [Element: Int] { reduce(into: [:]) { $0[$1, default: 0] += 1 } }
}
Run Code Online (Sandbox Code Playgroud)
let values = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5]
let frequency = values.frequency
frequency[65] // 3
for (key, value) in frequency {
print("Element:", key, "count:", value)
}
Run Code Online (Sandbox Code Playgroud)
那些会打印
Element: 27.5 count: 1
Element: 30.25 count: 2
Element: 55.5 count: 2
Element: 65 count: 3
Run Code Online (Sandbox Code Playgroud)
您可以枚举数组并将值添加到字典中。
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)
Run Code Online (Sandbox Code Playgroud)
或者你可以在数组上执行 foreach :
array.forEach { (item) in
dictionary[item] = dictionary[item] ?? 0 + 1
}
print(dictionary)
Run Code Online (Sandbox Code Playgroud)
或者正如@rmaddy 所说:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3822 次 |
| 最近记录: |