ios-如何计算Swift数组中元素的出现次数?

我已经看到了一些这样的示例,但是所有这些似乎都依赖于知道要计算发生次数的元素。 我的数组是动态生成的,所以我无法知道我要计算哪个元素的出现(我想计算所有元素的出现)。 有人可以建议吗?

提前致谢

编辑:

也许我应该更清楚一点,该数组将包含多个不同的字符串(例如["FOO", "FOO", "BAR", "FOOBAR"]

如何在不知道它们是什么的情况下计算foo,bar和foobar的出现?

Alex Chesters asked 2020-02-21T15:29:23Z
13个解决方案
96 votes

Swift 3和Swift 2:

您可以使用Array类型的字典来为Hashable中的每个项目建立计数:

let arr = ["FOO", "FOO", "BAR", "FOOBAR"]
var counts: [String: Int] = [:]

for item in arr {
    counts[item] = (counts[item] ?? 0) + 1
}

print(counts)  // "[BAR: 1, FOOBAR: 1, FOO: 2]"

for (key, value) in counts {
    print("\(key) occurs \(value) time(s)")
}

输出:

BAR occurs 1 time(s)
FOOBAR occurs 1 time(s)
FOO occurs 2 time(s)

斯威夫特4:

Swift 4引入了(SE-0165)在字典查找中包含默认值的功能,并且可以使用诸如ArrayHashable之类的操作来对结果值进行突变,因此:

counts[item] = (counts[item] ?? 0) + 1

变成:

counts[item, default: 0] += 1

这样一来,使用Array即可在一条简洁的行中轻松进行计数操作:

let arr = ["FOO", "FOO", "BAR", "FOOBAR"]
var counts: [String: Int] = [:]

arr.forEach { counts[$0, default: 0] += 1 }

print(counts)  // "["FOOBAR": 1, "FOO": 2, "BAR": 1]"

斯威夫特4:Array

Swift 4引入了Array的新版本,该版本使用Hashable变量来累加结果。 使用它,计数的创建真正变成了一行:

let arr = ["FOO", "FOO", "BAR", "FOOBAR"]
let counts = arr.reduce(into: [:]) { counts, word in counts[word, default: 0] += 1 }

print(counts)  // ["BAR": 1, "FOOBAR": 1, "FOO": 2]

或使用默认参数:

let counts = arr.reduce(into: [:]) { $0[$1, default: 0] += 1 }

最后,您可以将其扩展为Array,以便可以在包含Hashable项的任何数组上调用它:

extension Array where Element: Hashable {
    var histogram: [Element: Int] {
        return self.reduce(into: [:]) { counts, elem in counts[elem, default: 0] += 1 }
    }
}

尽管我将其更改为计算属性,但还是从这个问题中借用了这个想法。

vacawama answered 2020-02-21T15:30:21Z
77 votes
array.filter{$0 == element}.count
Ruben answered 2020-02-21T15:30:36Z
24 votes

使用Swift 5时,您可以根据需要选择以下7个Playground示例代码之一来计算数组中可哈希项的出现次数。


#1 使用NSCountedSetAnyIteratormap(_:)init(_:uniquingKeysWith:)下标

let array = [4, 23, 97, 97, 97, 23]
let dictionary = array.reduce(into: [:]) { counts, number in
    counts[number, default: 0] += 1
}
print(dictionary) // [4: 1, 23: 2, 97: 3]

#2。 使用NSCountedSet函数,AnyIterator函数和map(_:)init(_:uniquingKeysWith:)初始化程序

let array = [4, 23, 97, 97, 97, 23]

let repeated = repeatElement(1, count: array.count)
//let repeated = Array(repeating: 1, count: array.count) // also works

let zipSequence = zip(array, repeated)

let dictionary = Dictionary(zipSequence, uniquingKeysWith: { (current, new) in
    return current + new
})
//let dictionary = Dictionary(zipSequence, uniquingKeysWith: +) // also works

print(dictionary) // prints [4: 1, 23: 2, 97: 3]

#3。 使用NSCountedSetAnyIterator初始化程序和map(_:)方法

let array = [4, 23, 97, 97, 97, 23]

let dictionary = Dictionary(grouping: array, by: { $0 })

let newDictionary = dictionary.mapValues { (value: [Int]) in
    return value.count
}

print(newDictionary) // prints: [97: 3, 23: 2, 4: 1]

#4。 使用NSCountedSetAnyIterator初始化程序和map(_:)方法

let array = [4, 23, 97, 97, 97, 23]

let dictionary = Dictionary(grouping: array, by: { $0 })

let newArray = dictionary.map { (key: Int, value: [Int]) in
    return (key, value.count)
}

print(newArray) // prints: [(4, 1), (23, 2), (97, 3)]

#5。 使用for循环和NSCountedSetAnyIterator下标

extension Array where Element: Hashable {

    func countForElements() -> [Element: Int] {
        var counts = [Element: Int]()
        for element in self {
            counts[element] = (counts[element] ?? 0) + 1
        }
        return counts
    }

}

let array = [4, 23, 97, 97, 97, 23]
print(array.countForElements()) // prints [4: 1, 23: 2, 97: 3]

#6。 使用NSCountedSetAnyIteratormap(_:)方法(需要Foundation)

import Foundation

extension Array where Element: Hashable {

    func countForElements() -> [(Element, Int)] {
        let countedSet = NSCountedSet(array: self)
        let res = countedSet.objectEnumerator().map { (object: Any) -> (Element, Int) in
            return (object as! Element, countedSet.count(for: object))
        }
        return res
    }

}

let array = [4, 23, 97, 97, 97, 23]
print(array.countForElements()) // prints [(97, 3), (4, 1), (23, 2)]

#7。 使用NSCountedSetAnyIterator(需要Foundation)

import Foundation

extension Array where Element: Hashable {

    func counForElements() -> Array<(Element, Int)> {
        let countedSet = NSCountedSet(array: self)
        var countedSetIterator = countedSet.objectEnumerator().makeIterator()
        let anyIterator = AnyIterator<(Element, Int)> {
            guard let element = countedSetIterator.next() as? Element else { return nil }
            return (element, countedSet.count(for: element))
        }
        return Array<(Element, Int)>(anyIterator)
    }

}

let array = [4, 23, 97, 97, 97, 23]
print(array.counForElements()) // [(97, 3), (4, 1), (23, 2)]

学分:

  • 迅速成语
  • 使用字典在集合上通用
Imanou Petit answered 2020-02-21T15:31:40Z
9 votes

我更新了oisdk对Swift2的回答。

14/04/14我将此代码更新为Swift2.2

16/10/11更新为Swift3


可散列:

extension Sequence where Self.Iterator.Element: Hashable {
    private typealias Element = Self.Iterator.Element

    func freq() -> [Element: Int] {
        return reduce([:]) { (accu: [Element: Int], element) in
            var accu = accu
            accu[element] = accu[element]?.advanced(by: 1) ?? 1
            return accu
        }
    }
}

平等的:

extension Sequence where Self.Iterator.Element: Equatable {
    private typealias Element = Self.Iterator.Element

    func freqTuple() -> [(element: Element, count: Int)] {

        let empty: [(Element, Int)] = []

        return reduce(empty) { (accu: [(Element, Int)], element) in
            var accu = accu
            for (index, value) in accu.enumerated() {
                if value.0 == element {
                    accu[index].1 += 1
                    return accu
                }
            }

            return accu + [(element, 1)]
        }
    }
}

用法

let arr = ["a", "a", "a", "a", "b", "b", "c"]
print(arr.freq()) // ["b": 2, "a": 4, "c": 1]
print(arr.freqTuple()) // [("a", 4), ("b", 2), ("c", 1)]

for (k, v) in arr.freq() {
    print("\(k) -> \(v) time(s)")
}
// b -> 2 time(s)
// a -> 4 time(s)
// c -> 1 time(s)

for (element, count) in arr.freqTuple() {
    print("\(element) -> \(count) time(s)")
}
// a -> 4 time(s)
// b -> 2 time(s)
// c -> 1 time(s)
ken0nek answered 2020-02-21T15:32:22Z
3 votes

使用NSCountedSet。 在Objective-C中:

NSCountedSet* countedSet = [[NSCountedSet alloc] initWithArray:array];
for (NSString* string in countedSet)
    NSLog (@"String %@ occurs %zd times", string, [countedSet countForObject:string]);

我假设您可以自己将其转换为Swift。

gnasher729 answered 2020-02-21T15:32:47Z
3 votes

怎么样:

func freq<S: SequenceType where S.Generator.Element: Hashable>(seq: S) -> [S.Generator.Element:Int] {

  return reduce(seq, [:]) {

    (var accu: [S.Generator.Element:Int], element) in
    accu[element] = accu[element]?.successor() ?? 1
    return accu

  }
}

freq(["FOO", "FOO", "BAR", "FOOBAR"]) // ["BAR": 1, "FOOBAR": 1, "FOO": 2]

它是通用的,因此可以与您的任何元素一起使用,只要它是可哈希的即可:

freq([1, 1, 1, 2, 3, 3]) // [2: 1, 3: 2, 1: 3]

freq([true, true, true, false, true]) // [false: 1, true: 4]

而且,如果您无法使元素可散列,则可以使用元组来实现:

func freq<S: SequenceType where S.Generator.Element: Equatable>(seq: S) -> [(S.Generator.Element, Int)] {

  let empty: [(S.Generator.Element, Int)] = []

  return reduce(seq, empty) {

    (var accu: [(S.Generator.Element,Int)], element) in

    for (index, value) in enumerate(accu) {
      if value.0 == element {
        accu[index].1++
        return accu
      }
    }

    return accu + [(element, 1)]

  }
}

freq(["a", "a", "a", "b", "b"]) // [("a", 3), ("b", 2)]
oisdk answered 2020-02-21T15:33:15Z
3 votes

我喜欢避免内部循环,并尽可能使用.map。因此,如果我们有一个字符串数组,我们可以执行以下操作来计算出现次数

var occurances = ["tuples", "are", "awesome", "tuples", "are", "cool", "tuples", "tuples", "tuples", "shades"]

var dict:[String:Int] = [:]

occurances.map{
    if let val: Int = dict[$0]  {
        dict[$0] = val+1
    } else {
        dict[$0] = 1
    }
}

版画

["tuples": 5, "awesome": 1, "are": 2, "cool": 1, "shades": 1]
EmilDo answered 2020-02-21T15:33:40Z
1 votes

另一种方法是使用过滤器方法。 我觉得最优雅

var numberOfOccurenses = countedItems.filter(
{
    if $0 == "FOO" || $0 == "BAR" || $0 == "FOOBAR"  {
        return true
    }else{
        return false
    }
}).count
user1700737 answered 2020-02-21T15:34:00Z
0 votes
public extension Sequence {

    public func countBy<U : Hashable>(_ keyFunc: (Iterator.Element) -> U) -> [U: Int] {

    var dict: [U: Int] = [:]
    for el in self {
        let key = keyFunc(el)
        if dict[key] == nil {
            dict[key] = 1
        } else {
            dict[key] = dict[key]! + 1
        }

        //if case nil = dict[key]?.append(el) { dict[key] = [el] }
    }
    return dict
}


let count = ["a","b","c","a"].countBy{ $0 }
// ["b": 1, "a": 2, "c": 1]


struct Objc {
    var id: String = ""

}

let count = [Objc(id: "1"), Objc(id: "1"), Objc(id: "2"),Objc(id: "3")].countBy{ $0.id }

// ["2": 1, "1": 2, "3": 1]
Carlos Chaguendo answered 2020-02-21T15:34:15Z
0 votes
extension Collection where Iterator.Element: Comparable & Hashable {
    func occurrencesOfElements() -> [Element: Int] {
        var counts: [Element: Int] = [:]
        let sortedArr = self.sorted(by: { $0 > $1 })
        let uniqueArr = Set(sortedArr)
        if uniqueArr.count < sortedArr.count {
            sortedArr.forEach {
                counts[$0, default: 0] += 1
            }
        }
        return counts
    }
}

// Testing with...
[6, 7, 4, 5, 6, 0, 6].occurrencesOfElements()

// Expected result (see number 6 occurs three times) :
// [7: 1, 4: 1, 5: 1, 6: 3, 0: 1]
iKK answered 2020-02-21T15:34:31Z
0 votes

您可以使用此功能来计算数组中项目的出现

func checkItemCount(arr: [String]) {       
    var dict = [String: Any]()

    for x in arr {  
        var count = 0 
        for y in arr {
            if y == x {
                count += 1
            }
        }

        dict[x] = count
    }

    print(dict)
}

您可以这样实现它-

let arr = ["FOO", "FOO", "BAR", "FOOBAR"]
checkItemCount(arr: arr)
Rahul Khatri answered 2020-02-21T15:34:55Z
0 votes

斯威夫特4

let array = ["FOO", "FOO", "BAR", "FOOBAR"]

// Merging keys with closure for conflicts
let mergedKeysAndValues = Dictionary(zip(array, repeatElement(1, count: array.count)), uniquingKeysWith: +) 

// mergedKeysAndValues is ["FOO": 2, "BAR": 1, "FOOBAR": 1]
ViciV answered 2020-02-21T15:35:15Z
-1 votes

计数排序的第一步。

var inputList = [9,8,5,6,4,2,2,1,1]
var countList : [Int] = []

var max = inputList.maxElement()!

// Iniate an array with specific Size and with intial value.
// We made the Size to max+1 to integrate the Zero. We intiated the array with Zeros because it's Counting.

var countArray = [Int](count: Int(max + 1), repeatedValue: 0)

for num in inputList{
    countArray[num] += 1
}

print(countArray)
Abo3atef answered 2020-02-21T15:35:35Z
translate from https://stackoverflow.com:/questions/30545518/how-to-count-occurrences-of-an-element-in-a-swift-array