2016-02-29 88 views
-1

如何在scala列表中使用group? 我是初学者在我的代码m得到一些记录列表,我想在列表中使用group。这里是我的名单例如如何根据scala中的值对列表进行分组?

List((smith,swarm_4,group_2,400,1200), (smith,swarm_5,group_2,400,1200), 
    (Michel,swarm_4,group_2,400,400), (smith,swarm_6,group_3,400,1200),  
    (smith,swarm_7,group_3,400,1200), (Michel,swarm_4,group_2,300,200), 
    (Michel,swarm_5,group_2,400,400), (Michel,swarm_6,group_3,400,400), 
    (Michel,swarm_7,group_3,400,400), (smith,swarm_5,group_2,100,200) 
) 

假设列表中包含这种格式记录(名称:字符串,群:字符串,组:字符串,TX:龙,接收:长)。 我想分组(群组和群组)和组匹配然后聚合(Tx + Tx)和(Rx + Rx)。

如:

(smith,swarm_5,group_2,400,1200) and (smith,swarm_5,group_2,100,200) ==> 
((swarm_5,group_2) => (400+100, 1200+200) => output(smith,swarm_5,group_2,500,1400)) 

使输出变得像

List((smith,swarm_4,group_2,400,1200), (smith,swarm_5,group_2,500,1400), 
     (Michel,swarm_4,group_2,700,600), (smith,swarm_6,group_3,400,1200), 
     (smith,swarm_7,group_3,400,1200), (Michel,swarm_5,group_2,400,400), 
     (Michel,swarm_6,group_3,400,400), (Michel,swarm_7,group_3,400,400)) 

请给我建议任何想法或通过任何其他的想法在斯卡拉编码使用组。

+0

你有什么已经尝试过,有什么问题你遇到了?有关询问好问题的信息,请参阅此处:http://stackoverflow.com/help/mcve – Dima

回答

1

此代码应该适用于您定列表

var outList = inList.map(x => ((x._1,x._2,x._3),x._4,x._5))) 
     .groupBy(_._1) 
     .map{case (key,value) => 
       value.reduce((x,y) => (x._1,(x._2._1+y._2._1,x._2._2+y._2._2)))}; 
相关问题