gpt4 book ai didi

scala - Scala-如何从Tuple2s的集合构建一个不变的 map ?

转载 作者:行者123 更新时间:2023-12-03 13:46:23 24 4
gpt4 key购买 nike

在Python中,可以从可重复的元组集合构造字典:

>>> listOfTuples = zip(range(10), [-x for x in range(10)])
>>> listOfTuples
[(0, 0), (1, -1), (2, -2), (3, -3), (4, -4), (5, -5), (6, -6), (7, -7), (8, -8), (9, -9)]
>>> theDict = dict(listOfTuples)
>>> theDict
{0: 0, 1: -1, 2: -2, 3: -3, 4: -4, 5: -5, 6: -6, 7: -7, 8: -8, 9: -9}
>>>

是否有等效的Scala语法?我看到您可以使用varargs类型的Tuple2s来构建 map ,例如
scala> val theMap = Map((0,0),(1,-1))
theMap: scala.collection.immutable.Map[Int,Int] = Map((0,0), (1,-1))

scala> theMap(0)
res4: Int = 0

scala> theMap(1)
res5: Int = -1

scala> val tuplePairs = List((0,0),(1,-1))
tuplePairs: List[(Int, Int)] = List((0,0), (1,-1))

scala> val mapFromIterable = Map(tuplePairs)
<console>:6: error: type mismatch;
found : List[(Int, Int)]
required: (?, ?)
val mapFromIterable = Map(tuplePairs)
^

我可以遍历并手动分配每个值,但是似乎必须有一个更好的方法。
scala> var theMap:scala.collection.mutable.Map[Int,Int] = scala.collection.mutable.Map()   
theMap: scala.collection.mutable.Map[Int,Int] = Map()

scala> tuplePairs.foreach(x => theMap(x._1) = x._2)

scala> theMap
res13: scala.collection.mutable.Map[Int,Int] = Map((1,-1), (0,0))

最佳答案

使用Scala 2.8.0 final,您可以这样做:


scala> val tuplePairs = List((0,0),(1,-1))
tuplePairs: List[(Int, Int)] = List((0,0), (1,-1))

scala> tuplePairs.toMap
res0: scala.collection.immutable.Map[Int,Int] = Map((0,0), (1,-1))

如果您使用的是Scala 2.7.7,则可以执行以下操作,以替代您使用的方法:

scala> val tuplePairs = List((0,0),(1,-1))
tuplePairs: List[(Int, Int)] = List((0,0), (1,-1))

scala> Map(tuplePairs: _*)
res2: scala.collection.immutable.Map[Int,Int] = Map(0 -> 0, 1 -> -1)

但是正如您所看到的,在2.8.0中,已有很多改进。

关于scala - Scala-如何从Tuple2s的集合构建一个不变的 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3323651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com