gpt4 book ai didi

objective-c - iOS:从字典中获取矩阵

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:46:41 28 4
gpt4 key购买 nike

我有一个以这种方式组织的字典数组:

[0] {@"code", 1} {@"category","drink"} ...and other value that aren't important
[1] {@"code", 2} {@"category","drink"}
[2] {@"code", 3} {@"category","drink"}
[3] {@"code", 4} {@"category","food"}
[4] {@"code", 5} {@"category","food"}
[5] {@"code", 6} {@"category","drink"}

以这种方式获得矩阵(数组的数组)的最佳方法是什么...

[0] {1,2,3,6}
[1] {4,5}

你能帮帮我吗?

最佳答案

所以如果你有字典数组:

NSArray *originalArray = @[
@{@"code": @1, @"category":@"drink"},
@{@"code": @2, @"category":@"drink"},
@{@"code": @3, @"category":@"drink"},
@{@"code": @4, @"category":@"food"},
@{@"code": @5, @"category":@"food"},
@{@"code": @6, @"category":@"drink"}
];

你可以通过类似的方式得到你想要的东西:

NSMutableArray *arrayOfCategories = [NSMutableArray array];
NSMutableArray *arrayOfArrayOfCodes = [NSMutableArray array];

for (NSDictionary *originalArrayEntry in originalArray)
{
NSString *category = originalArrayEntry[@"category"];
NSString *code = originalArrayEntry[@"code"];

NSInteger indexInArrayOfCategories = [arrayOfCategories indexOfObject:category];
NSMutableArray *arrayOfCodes;
if (indexInArrayOfCategories == NSNotFound)
{
indexInArrayOfCategories = [arrayOfCategories count];
arrayOfCodes = [NSMutableArray array];
[arrayOfArrayOfCodes addObject:arrayOfCodes];
[arrayOfCategories addObject:category];
}
else
{
arrayOfCodes = arrayOfArrayOfCodes[indexInArrayOfCategories];
}

[arrayOfCodes addObject:code];
}

NSLog(@"arrayOfArrayOfCodes = %@", arrayOfArrayOfCodes);
NSLog(@"arrayOfCategories = %@", arrayOfCategories);

请注意,您没有要求类别值数组,但我认为您要求的结果集在没有它的情况下毫无意义。

就个人而言,如果我想完成您的要求(并消除对单独数组的需求)并且顺序不重要,我可能会倾向于使用数组值的字典(由类别值键入)代码,例如由以下原因产生的东西:

NSMutableDictionary *resultDictionary = [NSMutableDictionary dictionary];

for (NSDictionary *originalArrayEntry in originalArray)
{
NSString *category = originalArrayEntry[@"category"];
NSString *code = originalArrayEntry[@"code"];

NSMutableArray *arrayForCategory = resultDictionary[category];
if (!arrayForCategory)
{
arrayForCategory = [NSMutableArray array];
resultDictionary[category] = arrayForCategory;
}

[arrayForCategory addObject:code];
}

NSLog(@"resultDictionary = %@", resultDictionary);

关于objective-c - iOS:从字典中获取矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13826530/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com