我迷失在排序描述符,词典和计数集的海洋中。希望有人能帮助我找到一种更简单的方法。
从这样的排序数组开始(NSNumbers):
['7','7','7','5','5','5','5','5','5','3','2','2','2','2']
我希望最终得到一个排序的字典数组,如下所示:
{'5','6'} //the number 5 appeared 6 times
{'2','4'} //the number 2 appeared 4 times
{'7','3'} //the number 7 appeared 3 times
{'3','1'} //the number 3 appeared 1 time
答案 0 :(得分:5)
以下是根据NSCountedSet
NSArray *numbers = @[@7,@7,@7,@5,@5,@5,@5,@5,@5,@3,@2,@2,@2,@2];
NSCountedSet *countedSet = [NSCountedSet setWithArray:numbers];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSNumber *num in countedSet) {
NSUInteger c = [countedSet countForObject:num];
[result setObject:@(c) forKey:num];
}