D 中 Scala groupBy 的等价物是什么?

What is the equivalent of Scala groupBy in D?

每当您想在 Scala 中创建频率 Map 时,您可以轻松地对集合调用 .groupBy

val seq = Seq("a", "a", "b", "c", "b", "a")
seq.groupBy(a => a) // Map(b -> List(b, b), a -> List(a, a, a), c -> List(c))

嵌套集合也很容易做到这一点。

val nseq = Seq(Seq("a", 1), Seq("a", -1), Seq("b", -5), Seq("c", 100), Seq("b", 5), Seq("a", 0))
nseq.groupBy(a => a(0)) // Map(b -> List(List(b, -5), List(b, 5)), a -> List(List(a, 1), List(a, -1), List(a, 0)), c -> List(List(c, 100)))

注意每个键的值是如何聚合在一起的。

我试图在 D 中找到类似的函数并找到 group。它的工作方式有些不同,因为它是 returns 元组对。

int[] arr = [1, 1, 2, 2, 3, 2, 2, 5];
arr.sort.group; // [Tuple!(int, uint)(1, 2), Tuple!(int, uint)(2, 4), Tuple!(int, uint)(3, 1), Tuple!(int, uint)(5, 1)]
arr.sort.group.assocArray; // [5:1, 3:1, 2:4, 1:2]

但是,当涉及到嵌套集合时。

Tuple!(string, int)[] arr = [tuple("a", 1), tuple("a", -1), tuple("b", 2), tuple("b", 25), tuple("c", 100), tuple("b", 21)];
arr.sort!("a[0] > b[0]").group!((a, b) => a[0] == b[0]); //(Tuple!(string, int)("c", 100), 1), (Tuple!(string, int)("b", 25), 3), (Tuple!(string, int)("a", 1), 2)]

不会发生值聚合,只会采用第一个值。但是只取一个第一个值有什么用呢?当然可以通过

规避这一点
int[][string] res;
arr.each!(s => res[s[0]] ~= [s[1]]);
writeln(res) // ["c":[100], "a":[1, -1], "b":[25, 2, 21]]

但是是否可以在不预定义 res 数组的情况下在一行中完成此操作?

Tuple!(string, int)[] arr = [tuple("a", 1), tuple("a", -1), tuple("b", 2), tuple("b", 25), tuple("c", 100), tuple("b", 21)];
arr.sort!("a[0] > b[0]").group!((a, b) => a[0] == b[0]); // [Tuple!(string, int)("b", 25):3, Tuple!(string, int)("c", 100):1, Tuple!(string, int)("a", 1):2]

这不是我得到的结果:

https://run.dlang.io/is/9lVPkv

结果是 [tuple(tuple("c", 100), 1), tuple(tuple("b", 25), 3), tuple(tuple("a", 1), 2)],看起来是正确的。

but is it possible to this in one line without predefining res array?

我想你在找 chunkBy:

arr.sort!("a[0] > b[0]").chunkBy!((a, b) => a[0] == b[0]).each!writeln;

这个results in:

[Tuple!(string, int)("c", 100)]
[Tuple!(string, int)("b", 25), Tuple!(string, int)("b", 2), Tuple!(string, int)("b", 21)]
[Tuple!(string, int)("a", 1), Tuple!(string, int)("a", -1)]