简体   繁体   English

如何在Scala中访问列表中的列表元素

[英]How to access an element of list within a list in scala

I want to access elements of a list within one list and check whether the elements are greater than a minimum value. 我想访问一个列表中一个列表的元素,并检查这些元素是否大于最小值。 Example: List[([1,2],0.3), ([1.5,6],0.35), ([4,10],0.25), ([7,15],0.1)] 示例:List [([1,2],0.3),([1.5,6],0.35),([4,10],0.25),([7,15],0.1)]
Let the minimum value: 1 设最小值:1
The result should be: List[([1,6],0.65), ([4,10],0.25), ([7,15],0.1)] 结果应为:List [([[1,6],0.65),([4,10],0.25),([7,15],0.1)]
As 1.5-1 is less than minimum value 1, it will merge the elements [1,2],0.3) and ([1.5,6],0.35) as [1, 6], 0.65, meaning it will take the 1st element of the inside list and last element of the 2nd element of the outside list and the 2nd element of the outside list will be added (0.3+0.35). 因为1.5-1小于最小值1,它将合并元素[1,2],0.3)和([1.5,6],0.35)为[1,6],0.65,这意味着它将采用第一个元素内部列表的第一个元素和外部列表的第二个元素以及外部列表的第二个元素的最后一个元素将被添加(0.3 + 0.35)。 This will be done for all elements of the outside list. 将对外部列表的所有元素执行此操作。 The code I tried is written below: 我尝试的代码如下所示:

def reduce (d1:List[(Interval, Rational)]): List[(Interval, Rational)] =
{
    var z = new ListBuffer[(Interval, Rational)]()
    def recurse (list: List[(Interval, Rational)]): Unit = list match { 
        case List(x, y, _*) if ((y._1_1 - x._1_1) < min_val) => 
           val i = x._1_1; y._1_2 
           val w = x._2 + y._2
           z += (i,w)
          else
           z += x
           recurse(list.tail)
        case Nil =>
   }
   z.toList
}  

But this is not working. 但这是行不通的。 Please help me to fix this. 请帮助我解决此问题。

OK, what you've written really isn't Scala code, and I had to make a few modifications just to get a compilable example, but see if this works for you. 好的,您编写的实际上不是Scala代码,为了获得可编译的示例,我不得不进行一些修改,但是请看这是否对您有用。

type Interval = (Double,Double)
type Rational = Double
def reduce (lir:List[(Interval, Rational)]): List[(Interval, Rational)] = {
  val minVal = 1.0
  lir.foldLeft(List.empty[(Interval, Rational)]){
    case (a, b) if a.isEmpty => List(b)
    case (acc, ((i2a, i2b), r2)) => 
      val ((i1a, _), r1) = acc.head
      if (i2a - i1a < minVal) ((i1a, i2b), r1 + r2) :: acc.tail
      else ((i2a, i2b), r2) :: acc
  }.reverse
}

Test case: 测试用例:

reduce(List( ((1.0,2.0),0.3), ((1.5,6.0),0.35), ((4.0,10.0),0.25), ((7.0,15.0),0.1) ))
// result: List[(Interval, Rational)] = List(((1.0,6.0),0.6499999999999999), ((4.0,10.0),0.25), ((7.0,15.0),0.1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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