组合 NSArray

发布于 2024-12-26 01:59:16 字数 237 浏览 5 评论 0原文

我有 3 个 NSArray,其中:

item: amount

A: 1
B: 2
C: 3

A: 2
E: 1
F: 6

C: 5
D: 1
F: 3

将它们“组合”为一个后,我需要:

A: 3
B: 2
C: 8
D: 1
E: 1
F: 9

我是否首先将所有数组组合为一个,然后求和并删除重复项?

I have 3 NSArrays with:

item: amount

A: 1
B: 2
C: 3

A: 2
E: 1
F: 6

C: 5
D: 1
F: 3

After "combining" these into one, I need:

A: 3
B: 2
C: 8
D: 1
E: 1
F: 9

Do I first combine all the arrays into one and then sum and remove the duplicates?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

影子是时光的心 2025-01-02 01:59:16

您可以使用 NSCountedSet。我不清楚数组中数据的结构,但假设您的 B: 2 意味着数组中有两个 B,那么这样的事情就可以工作:

NSCountedSet *set = [NSCountedSet setWithCapacity:[array1 count]+[array2 count]+[array3 count]];
[set addObjectsFromArray:array1];
[set addObjectsFromArray:array2];
[set addObjectsFromArray:array3];

// Test it out!
NSUInteger countForC = [set countForObject:objC];
// countForC == 8

You could use an NSCountedSet. I'm not clear on the structure of the data in your arrays, but by assuming that your B: 2 means that you have two B's in the array, then something like this would work:

NSCountedSet *set = [NSCountedSet setWithCapacity:[array1 count]+[array2 count]+[array3 count]];
[set addObjectsFromArray:array1];
[set addObjectsFromArray:array2];
[set addObjectsFromArray:array3];

// Test it out!
NSUInteger countForC = [set countForObject:objC];
// countForC == 8
蓝眼泪 2025-01-02 01:59:16

您可以尝试使用 NSMutableDictionary,而不是使用 NSArray,其中键是对象结构中固有的。这将允许您迭代每个字母和计数数组,然后使用键查询值,获取值并添加到值中,然后继续处理。

Instead of using a NSArray you could try using a NSMutableDictionary where the key is inherent in the objects structure. That will allow you to iterate through each of your arrays of letters and counts then query for the value with the key, get the value and add to the value, then continue processing.

风向决定发型 2025-01-02 01:59:16

一种可能性是使用:

可能需要探讨性能方面的考虑因素。或者,迭代数组,在单独的 NSDictionary 中提取匹配的项目(在项目上键入)并随时求和。

One possibility would be to use:

  • Use predicates to extract like sets of data (by item) into separate arrays. See Collection predicates guide
  • Key Value Coding to sum the value field of each of the resulting arrays (by item). See KVO collection operators.
  • Pop the results in whatever structure you like (NSArray or NSDictionary).

There may be performance considerations to explore. Alternatively, iterate the array, pulling out matching items in a separate NSDictionary (keyed on item) and summing as you go.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文