【发布时间】:2017-08-23 23:13:41
【问题描述】:
在 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 来构建地图,例如
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))
【问题讨论】: