有条件地合并列表元素 [英] Conditionally merge list elements

查看:45
本文介绍了有条件地合并列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据一些表达式有条件地合并列表中彼此后面的元素.一个更好地解释我想做什么的例子:

I want to conditionally merge elements following eachother in a list based on some expression. An example to better explain what I would like to do:

来自:

val list = List("a1", "a2", "b1", "b2", "b3", "a3", "a4")

我想将所有以 b 开头的元素合并为一个元素,以获得这样的结果列表:

I would like to merge all elements starting with b into a single element to get a resulting list like this:

List("a1", "a2", "b1-b2-b3", "a3", "a4")

在我的用例中,b 元素总是按顺序排列,但 b 元素的数量可以从没有元素到数十个元素不等.

In my use case, the b-elements always follow in sequence but the number of b-elements can vary from no elements to tens of elements.

我试过做类似的事情

list.foldLeft("")((s1, s2) => if (s1.matches("""b\d""") && s2.matches("""b\d""")) s1 + "-" + s2 else s1)

但它并没有给我带来任何有用的东西.

but it doesn't render me anything useful.

关于如何解决这个问题有什么建议吗?

Any suggestions on how to approach this?

推荐答案

可以通过 foldLeft 并查看列表中最近插入的元素来完成:

It can be done with a foldLeft and looking at the most recently inserted element of the list:

list.foldLeft(List[String]()) {
  case (Nil, str) => str :: Nil
  case (head :: tail, str) =>
    if (head(0) == 'b' && str(0) == 'b') (s"$head-$str") :: tail
    else str :: head :: tail
}.reverse 
//> res0: List[String] = List(a1, a2, b1-b2-b3, a3, a4)

模式匹配也可以重写(如果你觉得更清晰):

The pattern match can also be rewritten (if you find it clearer):

list.foldLeft(List[String]()) {
  case (head :: tail, str) if (head(0) == 'b' && str(0) == 'b') =>
    (s"$head-$str") :: tail
  case (other, str) =>
    str :: other
}.reverse    

这篇关于有条件地合并列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆