【问题标题】:Return most common values in an array in Cocoa返回 Cocoa 中数组中最常见的值
【发布时间】:2012-09-26 11:59:40
【问题描述】:

Python 有一个集合库。在我的 Web 应用程序中,我使用 collections.Counter(aList).most_common([n]) 来返回 naList 中最常见的项目。

不错,简洁,相当快。

现在我正在开发一个 iOS 应用程序。 Objective-C 或 Cocoa 框架中是否有任何东西可以为字符串数组提供相同的功能?

假设aListNSArraryNSStrings

NSMutableDictionary *aCounter = [NSMutableDictionary dictionaryWithCapacity:[aList count]];
for aString in aList {
    NSUInteger keyCount = [aCounter valueForKey:aString];
    if keyCount == nil {
        [aCounter setValue:1 forKey:aString];
    }
    else {
        [aCounter setValue:(keyCount+1) forKey:aString];
    }

对压缩此内容或改进其性能有何建议?

【问题讨论】:

    标签: arrays cocoa-touch collections counter


    【解决方案1】:

    在我的手机上,但这应该能让你走到一半:

    NSArray *input = ...
    NSCountedSet *set = [[NSCountedSet alloc] initWithArray:input];
    NSMutableDictionary *output = [[NSMutableDictionary alloc] init];
    for (id elem in set) [output setObject:[set countForObject:elem] forValue:elem];
    

    如果这还不够快,我会考虑在插入时进行优化。

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 1970-01-01
      • 2015-08-18
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多