Scala:将Map应用于元组列表 [英] Scala: apply Map to a list of tuples

查看:118
本文介绍了Scala:将Map应用于元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个非常简单的问题:我想做这样的事情:

  var arr1:Array [Double] = ... 
var arr2:Array [Double] = ...

var arr3:Array [(Double,Double)] = arr1.zip(arr2)

arr3 .foreach(x => {if(x._1>阈值){x._2 = x._2 *因子}})

我尝试了很多不同的语法版本,但都失败了。我该如何解决?

谢谢!

解决方案

解决此问题的多种方法,例如考虑使用 collect ,它提供了一个不变的集合 arr4 ,如下所示,

  val arr4 = arr3.collect {如果x>阈值=> (x,y *因数)
情况v => v
}

有了这样的理解力,

 对于((x,y)<-arr3)
收益(x,如果(x>阈值)y *因数y)


very simple question: I want to do something like this:

var arr1: Array[Double] = ...
var arr2: Array[Double] = ...

var arr3: Array[(Double,Double)] = arr1.zip(arr2)

arr3.foreach(x => {if (x._1 > treshold) {x._2 = x._2 * factor}})

I tried a lot differnt syntax versions, but I failed with all of them. How could I solve this? It can not be very difficult ...

Thanks!

解决方案

Multiple approaches to solve this, consider for instance the use of collect which delivers an immutable collection arr4, as follows,

val arr4 = arr3.collect {
  case (x, y) if x > threshold => (x ,y * factor)
  case v => v 
}

With a for comprehension like this,

for ((x, y) <- arr3) 
  yield (x, if (x > threshold) y * factor else y)

这篇关于Scala:将Map应用于元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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