2016-02-29 87 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)))}; 
相關問題