根据其值和另一个数组的值更新一个数组 [英] Update an Array based on its values and the values of another Array

查看:160
本文介绍了根据其值和另一个数组的值更新一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据其他数组的值更改数组的值.特别是这些是我正在使用的数组:

I am trying to change the value of an array based on the value of a different array. In particular these are the arrays I am working with:

val inpoly: Array[Boolean]=Array(false, true, true, false)
val idx1: Array[Boolean]=Array(true, false, false, false)

我想检查数组idx1的位置,并在该位置上将inpoly设置为true,否则,只需保留inpoly已经具有的值即可.

I would like to check the array idx1 and where it is true I would like to set inpoly to true in that specific position, otherwise, just leave the value that inpoly already has.

我的预期结果是拥有这个数组:

My expected result would be to have this array:

final_vector= true, true, true, false

由于idx1的第一个值为true,所以将true分配给inpoly. idx1的所有其他值均为false,因此请保持inpoly不变

since the first value of idx1 is true, assign true to inpoly. All the other values of idx1 are false, so leave inpoly as it is

我尝试了以下代码:

idx1.map({
  case true => true
  case false => inpoly})

但是我得到以下结果:

res308: Array[Any] = Array(true, Array(false, true, true, false), Array(false, true, true, false), Array(false, true, true, false))

任何人都可以帮忙吗?

推荐答案

您似乎想在布尔对上使用或".这是使用||的一种方法,它是Scala的OR函数:

It looks like you'd like to use an "OR" on the pairs of booleans. Here's one approach using || which is Scala's OR function:

val updated = inpoly.zip(idx1).map(pair => pair._1 || pair._2)

这将为您提供

updated: Array[Boolean] = Array(true, true, true, false)

在这里,zip会将两个数组组合成一个成对的数组.然后,您将映射这些对,如果其中一个为true,则返回true;如果两个均为false,则返回false.

Here, zip will combine the two arrays into one array of pairs. Then you will map through those pairs and return a true if either are true and a false if both are false.

您还可以使用模式匹配:

You could also use a pattern match:

val updated = inpoly.zip(idx1).map {
 case (left, right) => left || right
 case _ => None 
}

如果一个数组的长度与另一个数组的长度不同,您将要考虑要做什么.

You'll want to think about what you will do in the case that one Array has a different length than the other.

并且,如果您坚持修改inpoly而不是创建新的数组,请执行以下操作:

And, if you insist on modifying inpoly rather than creating a new array, do the following:

var inpoly: Array[Boolean]=Array(false, true, true, false)
val idx1: Array[Boolean]=Array(true, false, false, false)

inpoly = inpoly.zip(idx1).map(pair => pair._1 || pair._2)

请注意,在这里,我们将inpoly声明为var,而不是val.但是,我建议将inpoly保留为val,并为该数组的更新版本创建一个新的val.在Scala中,建议使用不可变值,尽管这可能需要一些时间来习惯.

Note that here, we declare inpoly to be a var, not a val. However, I would instead suggest keeping inpoly as a val and creating a new val for the updated version of that array. Using immutable values is a recommended practice in Scala, though it can take some getting used to.

这篇关于根据其值和另一个数组的值更新一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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