如何从两个列表中创建地图? [英] How to create a map out of two lists?

查看:43
本文介绍了如何从两个列表中创建地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表

val a = List(1,2,3)
val b = List(5,6,7)

我想创建一个像这样的地图:

I'd like to create a Map like:

val h = Map(1->5, 2->6, 3->7) 

基本上遍历列表并分配键值对.

basically iterating thru both the lists and assigning key value pairs.

如何在 Scala 中正确地做到这一点?

How to do it properly in Scala?

推荐答案

您可以将列表zip 组合成一个元组列表,然后调用toMap:

You can zip the lists together into a list of tuples, then call toMap:

(a zip b) toMap

请注意,如果一个列表比另一个长,它将被截断.

Note that if one list is longer than the other, it will be truncated.

示例:

val a = List(1, 2, 3)
val b = List(5, 6, 7)

scala> (a zip b) toMap
res2: scala.collection.immutable.Map[Int,Int] = Map(1 -> 5, 2 -> 6, 3 -> 7)

截断:

val c = List("a", "b", "c", "d", "e")

scala> (a zip c) toMap
res3: scala.collection.immutable.Map[Int,String] = Map(1 -> a, 2 -> b, 3 -> c)

(c zip a) toMap
res4: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)

这篇关于如何从两个列表中创建地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆