如何计算数组中独特项的数量?
示例:
let array:Array<Int> = [1,3,2,4,6,1,3,2]
计算函数:
array.count
将会得到 8
但我想计算唯一的项,这将会得到 5
从Swift 1.2开始,Swift拥有本地的Set
类型。使用Set
构造函数从数组中创建一个集合,然后count
属性将告诉您有多少个唯一项:
let array = [1,3,2,4,6,1,3,2]
let set = Set(array)
print(set.count) // prints "5"
对于Swift 1.1及更早版本:
将您的数组转换为NSSet
:
let array = [1,3,2,4,6,1,3,2]
let set = NSSet(array: array)
println(set.count) // prints "5"
你可以在此处阅读更多相关内容。
如果您想知道每种物品有多少个,您可以使用字典来计数:
var counts = [Int:Int]()
for item in array {
counts[item] = (counts[item] ?? 0) + 1
}
print(counts) // prints "[6: 1, 2: 2, 3: 2, 1: 2, 4: 1]"
print(counts.count) // prints "5"
print("There are \(counts[1] ?? 0) ones.") // prints "There are 2 ones."
print("There are \(counts[7] ?? 0) sevens.") // prints "There are 0 sevens."
let array:Array<Int> = [1,3,2,4,6,1,3,2]
let count = NSSet(array: array).count
println(count)
5
实现函数countDistinct(numbers: [Int]),以返回数组中不同元素的数量。 Swift的NSSet文档 https://developer.apple.com/documentation/foundation/nsset
func countDistinct(numbers: [Int]) -> Int {
let array:Array<Int> = numbers
let count = NSSet(array: array).count
return count
}
print(countDistinct(numbers: [20, 10, 10, 30, 20]))
let start: (Int, Int?) = (0, nil)
let count = array.sorted(<).reduce(start) { initial, value in
(initial.0 + (initial.1 == value ? 0 : 1), value)
}
let uniqueElements = count.0
count
元组的元素0中。0
和nil
初始化start
元组,并将其作为初始值传递给在数组的排序副本上调用的reduce
方法。
在每次迭代中,返回一个新元组,其中包含当前的数组元素和当前计数器,如果当前元素与前一个元素不同,则将当前计数器增加一。func countUniques<T: Comparable>(_ array: Array<T>) -> Int {
let sorted = array.sorted()
let initial: (T?, Int) = (.none, 0)
let reduced = sorted.reduce(initial) {
($1, $0.0 == $1 ? $0.1 : $0.1 + 1)
}
return reduced.1
}