Arrays 返回Cocoa中数组中最常见的值

Arrays 返回Cocoa中数组中最常见的值,arrays,cocoa-touch,collections,counter,Arrays,Cocoa Touch,Collections,Counter,Python有一个集合库。在我的web应用程序中,我使用collections.Counter(aList).most_common([n])返回n列表中最常见的项目 好的,简洁的,相当快的 现在我正在开发一个iOS应用程序。objective-C或Cocoa框架中是否有任何东西可以为字符串数组提供相同的函数 假设aList是NSStrings的nsarray NSMutableDictionary *aCounter = [NSMutableDictionary dictionaryWithC

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

好的,简洁的,相当快的

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

假设
aList
NSStrings
nsarray

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];
    }

有什么关于压缩或改进其性能的建议吗?

在我的手机上,但这应该可以让你达到一半:

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];
如果这还不够快,我会考虑在插入时进行优化