Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
D中Scala groupBy的等价物是什么?_D - Fatal编程技术网

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

D中Scala groupBy的等价物是什么?,d,D,无论何时,只要您想在Scala中创建频率映射,就可以轻松地调用集合上的.groupBy val seq=seq(“a”、“a”、“b”、“c”、“b”、“a”) seq.groupBy(a=>a)//映射(b->List(b,b),a->List(a,a,a),c->List(c)) 嵌套集合也很容易做到这一点 Tuple!(string, int)[] arr = [tuple("a", 1), tuple("a", -1), tuple("b", 2), tuple("b", 25), t

无论何时,只要您想在Scala中创建频率
映射
,就可以轻松地调用集合上的
.groupBy

val seq=seq(“a”、“a”、“b”、“c”、“b”、“a”)
seq.groupBy(a=>a)//映射(b->List(b,b),a->List(a,a,a),c->List(c))
嵌套集合也很容易做到这一点

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)]
val nseq=Seq(Seq(“a”,1),Seq(“a”,“-1”),Seq(“b”,“-5”),Seq(“c”,100),Seq(“b”,5),Seq(“a”,0))
groupBy(a=>a(0))//映射(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中找到类似的函数,并找到
。它的工作方式有些不同,因为它返回元组对

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
数组,是否可以在一行中实现这一点


这不是我得到的结果:

它的结果是
[元组(元组(“c”,100),1),元组(元组(“b”,25),3),元组(元组(“a”,1),2)]
,看起来是正确的

但是,不预先定义
res
数组,是否可以在一行中实现这一点

我想你在寻找:

这:


“这不是我得到的结果”——我可能在几个打开的选项卡之间复制粘贴。很抱歉。但它不会创建具有键和聚合值的关联数组。但是由于
chunkBy
文档指的是
groupBy
,所以我想这是我们在D中所能得到的。Phobos有
assocArray
,但不是
assocararray
之类的。无论如何,这几乎肯定更有效,因为排序和延迟返回切片不需要分配。
arr.sort!("a[0] > b[0]").chunkBy!((a, b) => a[0] == b[0]).each!writeln;
[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)]