如何使用map转换两个元组列表中的元组元素值

时间:2018-07-18 15:27:02

标签: scala

我有以下内容:

val x : List[(String, Int)] = List((mealOne,2), (mealTWo,1), (mealThree,2))

我想使用以下值和映射将String替换或转换为Int:

val餐一= 5.99;瓦尔餐二= 6.99;瓦尔餐三= 7.99

x.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))

那我该如何实现

谢谢

2 个答案:

答案 0 :(得分:0)

然后不要删除元组的第二个部分:

x.map{ x => (
  if (x._1 == "mealOne") mealOne
  else if (x._1 == "mealTwo") mealTwo 
  else mealThree,
  x._2
)}

当然,它适用于从StringDouble的任意映射:

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 REPL中:

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)