【问题标题】:List objects in array by frequency with most frequently occurring first [duplicate]按频率列出数组中最常出现的对象[重复]
【发布时间】:2016-12-23 08:48:35
【问题描述】:

我有几个数组要附加到一个新的更大的数组中,并期待一些重复,我需要按频率列出的新的更大数组中的所有对象。

例如:

a = ["Swift","iOS", "Parse"]
b = ["Swift", "iOS", "Parse"]
c = ["iOS", "Parse"]
d = ["Parse"]

let bigArray:[String] = a+b+c+d

如何从 bigArray 创建一个新数组,该数组按频率从高到低排序,不重复,所以它会打印:

["Parse", "iOS", "Swift"]

【问题讨论】:

    标签: ios arrays swift parse-platform


    【解决方案1】:
    let a = ["Swift","iOS", "Parse"]
    let b = ["Swift", "iOS", "Parse"]
    let c = ["iOS", "Parse"]
    let d = ["Parse"]
    
    var dictionary = [String: Int]()
    
    for value in a+b+c+d {
        let index = dictionary[value] ?? 0
        dictionary[value] = index + 1
    }
    
    let result = dictionary.sort{$0.1 > $1.1}.map{$0.0}
    print(result)
    //["Parse", "iOS", "Swift"]
    

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 2015-03-20
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多