我仍在学习使用Scala / Spark进行编码,我遇到了问题,非常感谢您的帮助。
我有一个Key和Double的Iterable。
Iterable [Key]是5个可能的键的子集说:
population
age
gender
height
weight
和Double是相应的阅读。
我的问题是,我希望以平面格式表示我的数据:
(Double,Double,Double,Double,Double)
对应于按特定顺序的键读数:
(population,age,gender,height,weight)
但是在没有键的Iterable中,我仍然需要用0填充它。例如:
Iterable((population,10),(age,21),(gender,0))
我希望能够将其表示为
(10,21,0,0,0) //the last 2 zeros are padded because there is no key matching height and weight.
到目前为止,我一直在为每个键进行单独匹配(如果存在,则复制Double,如果没有填充为零),但我想知道是否有一种巧妙的方法来执行此操作。
由于
答案 0 :(得分:2)
就个人而言,我会创建一个bottom: 0px
。所以说你得到了Map
:
Iterable
将其转换为地图:
val values = Seq(("population", 10), ("age", 21), ("gender", 0)).toIterable
当您从中提取值时,只需使用val keyValueMap = values.toMap
函数:
getOrElse
答案 1 :(得分:1)
我要做的是首先定义元素的顺序,所以,
val keyOrder = List("population", "age", "gender", "height", "weight")
接下来,您可以执行以下操作:
val valMap = Map("population" -> 199D, "gender" -> 1D, "weight" -> 50D)
keyOrder.map(k => valMap.getOrElse(k, 0D))