我有以下内容:
val x : List[(String, Int)] = List((mealOne,2), (mealTWo,1), (mealThree,2))
我想使用以下值和映射将String替换或转换为Int:
val餐一= 5.99;瓦尔餐二= 6.99;瓦尔餐三= 7.99x.map{ x => if (x._1 == "mealOne") mealOne
else if (x._1 == "mealTwo") mealTwo
else mealThree
}
结果:
List[Double] = List(5.99, 6.99, 7.99)
但是我想要这个:
List[Double,Int] = List((5.99,2), (6.99,1), (7.99,2))
那我该如何实现
谢谢
答案 0 :(得分:0)
然后不要删除元组的第二个部分:
x.map{ x => (
if (x._1 == "mealOne") mealOne
else if (x._1 == "mealTwo") mealTwo
else mealThree,
x._2
)}
当然,它适用于从String
到Double
的任意映射:
def replaceNamesByPrices(
nameToPrice: String => Double,
xs: List[(String, Int)]
): List[(Double, Int)] =
for ((name, amount) <- xs) yield (nameToPrice(name), amount)
,以便您随后可以将名称到价格的映射存储在地图中,即
val priceTable = Map(
"mealOne" -> 42.99,
"mealTwo" -> 5.99,
"mealThree" -> 2345.65
)
这样
replaceNamesByPrices(priceTable, x)
产生预期的结果。
答案 1 :(得分:0)
这是这样工作的:(仍然简化,这要归功于Andrey Tyukin):
for(m<-x) yield (y(m._1),m._2)
for((m,n)<-x) yield (y(m),n)
或
x.map(t=>(y(t._1),t._2))
x.map{case (m,n)=>(y(m),n)}
您的列表(输入):( y更改为Map)
val x = List(("mealOne",2), ("mealTWo",1), ("mealThree",2))
val y = Map(("mealOne",5.99), ("mealTWo",6.99), ("mealThree",7.99))
scala> for(m<-x) yield (y(m._1),m._2)
res35: List[(Double, Int)] = List((5.99,2), (6.99,1), (7.99,2))
scala> for((m,n)<-x) yield (y(m),n)
res60: List[(Double, Int)] = List((5.99,2), (6.99,1), (7.99,2))
scala> x.map(t=>(y(t._1),t._2))
res57: List[(Double, Int)] = List((5.99,2), (6.99,1), (7.99,2))
scala> x.map{case (m,n)=>(y(m),n)}
res59: List[(Double, Int)] = List((5.99,2), (6.99,1), (7.99,2)
)