计算特定整数在数组中的出现次数 [英] Count the occurences a particular integer has in an array

查看:32
本文介绍了计算特定整数在数组中的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算特定数字在数组中出现的次数.我找不到快速的方法.有人可以指导我吗?

How to count the number of times a particular number occurs in an array. I cant find a method for this for swift. can someone guide me please?

谢谢:)

推荐答案

Xcode 9 或更高版本 • Swift 4 或更高版本

在 Swift 4 中你可以使用新的 Dictionary 方法 reduce(into:) 如下:

In Swift 4 you can use the new Dictionary method reduce(into:) as follow:

extension Sequence where Element: Hashable {
    var frequency: [Element: Int] {
        return reduce(into: [:]) { $0[$1, default: 0] += 1 }
    }
    func frequency(of element: Element) -> Int {
        return frequency[element] ?? 0
    }
}

<小时>

游乐场测试:


Playground testing:

let numbers = [0, 0, 1, 1, 1, 2, 3, 4, 5, 5]
print(numbers.frequency) // [2: 1, 4: 1, 5: 2, 3: 1, 1: 3, 0: 2]

print(numbers.frequency(of: 0))   // 2  
print(numbers.frequency(of: 1))   // 3
print(numbers.frequency(of: 2))   // 1
print(numbers.frequency(of: 3))   // 1
print(numbers.frequency(of: 4))   // 1
print(numbers.frequency(of: 5))   // 2

通过扩展集合,它也支持字符串

By extending Collection it supports Strings as well

"aab".frequency   // ["a": 2, "b": 1]

这篇关于计算特定整数在数组中的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆