简体   繁体   中英

slice scala LIst by elements value

there is List like this

List(List(9, 1, 9), 
   List(9, 1, 8), 
   List(8, 2, 7), 
   List(8, 2, 6), 
   List(7, 3, 5), 
   List(7, 3, 4))

i want to slice list by second element, like this

List(List(List(9, 1, 9), List(9, 1, 8)), //second elem is "1"
     List(List(8, 2, 7), List(8,2,6)),   //second elem is "2"
     List(List(7, 3, 5), List(7,3,4)),    //second elem is "3"

I can do it by using verbose for loop, but it's too verbose. I also try to use span, but I fail to get second element. what is the best way?

val l = List(List(9, 1, 9),
    List(9, 1, 8),
    List(8, 2, 7),
    List(8, 2, 6),
    List(7, 3, 5),
    List(7, 3, 4))


  l.groupBy( {case first::second::tail => second} ).values.toList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM