如何使用scala从列表中删除重复值?

时间:2014-11-06 04:34:34

标签: list scala

我有以下列表

List(List
(43673,38448,512,36398,1500,**BpEwv+EcDv3z**,58f39535-03b7-4e05-a2d8-3f5b424c8938),
List(302750,759,512,759,3796,**BpEwv+EcDv3v**,069865df-30c3-48c3-bf02-79f2fcff7213),
List(616278,1600,512,107418,15255,**BpEwv+EcDv3v**,b373b731-6f38-4559-808e-1c05fc06af00),
List(0,0,512,0,0,**BpEwv+EcDv3z**,24894b9f-9e30-4073-a538-186a312c670e)
)

我想从此列表中删除以粗体标记的重复值(所有元素的列表的第6个索引)。元素序列是固定的。

预期产出:

List(
List(43673,38448,512,36398,1500,BpEwv+EcDv3z,58f39535-03b7-4e05-a2d8-3f5b424c8938),
List(302750,759,512,759,3796,BpEwv+EcDv3v,069865df-30c3-48c3-bf02-79f2fcff7213))

如何使用scala从列表中删除重复值?

2 个答案:

答案 0 :(得分:2)

如果要删除所有List中特定值的所有匹配项,可以使用以下代码:

val lss = List(List(1,2,2), List(1,2,3,4,2))

lss map (_.filter(_ != 2))           //  List(List(1), List(1, 3, 4))

删除所有2List的所有List

如果您想获得一个flatMap作为回报,可以使用lss flatMap (_.filter(_ != 2)) // List(1, 1, 3, 4)

{{1}}

答案 1 :(得分:1)

根据您的预期输出,您可以执行类似

的操作
scala> val a = List(List
 | (43673,38448,512,36398,1500,"BpEwv+EcDv3z","58f39535-03b7-4e05-a2d8-3f5b424c8938"),
 | List(302750,759,512,759,3796,"BpEwv+EcDv3v","069865df-30c3-48c3-bf02-79f2fcff7213"),
 | List(616278,1600,512,107418,15255,"BpEwv+EcDv3v","b373b731-6f38-4559-808e-1c05fc06af00"),
 | List(0,0,512,0,0,"BpEwv+EcDv3z","24894b9f-9e30-4073-a538-186a312c670e")
 | )
a: List[List[Any]] = List(List(43673, 38448, 512, 36398, 1500, BpEwv+EcDv3z, 58f39535-03b7-4e05-a2d8-3f5b424c8938), List(302750, 759, 512, 759, 3796, BpEwv+EcDv3v, 069865df-30c3-48c3-bf02-79f2fcff7213), List(616278, 1600, 512, 107418, 15255, BpEwv+EcDv3v, b373b731-6f38-4559-808e-1c05fc06af00), List(0, 0, 512, 0, 0, BpEwv+EcDv3z, 24894b9f-9e30-4073-a538-186a312c670e))

scala> a.groupBy(_(5)).mapValues(_(0)).map(_._2)
res0: scala.collection.immutable.Iterable[List[Any]] = List(List(302750, 759, 51
2, 759, 3796, BpEwv+EcDv3v, 069865df-30c3-48c3-bf02-79f2fcff7213), List(43673, 3
8448, 512, 36398, 1500, BpEwv+EcDv3z, 58f39535-03b7-4e05-a2d8-3f5b424c8938))

您也可以做一些更好的阅读

scala> a.groupBy(_(5)).mapValues(_(0)).values.toList
res6: List[List[Any]] = List(List(302750, 759, 512, 759, 3796, BpEwv+EcDv3v, 069865df-30c3-48c3-bf02-79f2fcff7213), List(43673, 38448, 512, 36398, 1500, BpEwv+EcDv3z, 58f39535-03b7-4e05-a2d83f5b424c8938))