日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

scala中map添加值_如何在Scala Map中反转键和值

發(fā)布時(shí)間:2025/3/11 编程问答 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 scala中map添加值_如何在Scala Map中反转键和值 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

scala中map添加值

A Map is a data structure that stores data as key: value pair.

映射是一種將數(shù)據(jù)存儲(chǔ)為鍵:值對的數(shù)據(jù)結(jié)構(gòu)。

Syntax:

句法:

Map(key->value, key->value)

反轉(zhuǎn)地圖中的鍵和值 (Reversing Keys and values in Map)

Here, we will see a program to reverse keys and values in Scala Map. We will reverse the values to keys and the keys to pairs.

在這里,我們將看到一個(gè)在Scala Map中反轉(zhuǎn)鍵和值程序 。 我們將值反轉(zhuǎn)為鍵,將鍵反轉(zhuǎn)為對。

So, before this, we will have to make sure that both keys and values of the initial map are unique to avoid errors.

因此,在此之前,我們必須確保初始映射的鍵和值都唯一以避免錯(cuò)誤。

Program:

程序:

object myObject { def main(args:Array[String]) { val bikes = Map(1->"S1000RR" , 2->"R1", 3->"F4" ) println("Inital map: " + bikes) val reverse = for ((a, b) <- bikes) yield (b, a) println("Reversed map: " + reverse) } }

Output

輸出量

Inital map: Map(1 -> S1000RR, 2 -> R1, 3 -> F4) Reversed map: Map(S1000RR -> 1, R1 -> 2, F4 -> 3)

Explanation:

說明:

Here, we have declared a map and then reversed its values. In the reverse variable, we have inserted value that is reverse of each pair of the original map, the yield methods take the (key, value) pair and returns (value, key) pair to the reverse map.

在這里,我們聲明了一個(gè)映射,然后反轉(zhuǎn)了它的值。 在反向變量中,我們插入了與原始映射的每對相反的值,yield方法采用( key,value )對,然后將( value,key )對返回到反向映射。

What if values are not unique?

如果值不是唯一的怎么辦?

There is a thing that is needed to be considered is both key-value pairs should be unique. But if we insert a duplicate in value, in the reverse map this will delete that pair.

有一點(diǎn)需要考慮的是,兩個(gè)鍵值對都應(yīng)該是唯一的。 但是,如果我們在值中插入重復(fù)項(xiàng),則在反向映射中將刪除該對。

Program:

程序:

object myObject { def main(args:Array[String]) { val bikes = Map(1->"S1000RR" , 2->"R1", 3->"F4", 4->"S1000RR" ) println("Inital map: " + bikes) val reverse = for ((a, b) <- bikes) yield (b, a) println("Reversed map: " + reverse) } }

Output

輸出量

Inital map: Map(1 -> S1000RR, 2 -> R1, 3 -> F4, 4 -> S1000RR) Reversed map: Map(S1000RR -> 4, R1 -> 2, F4 -> 3)

So, the code runs properly but the reverse will delete the pair 4->S100RR to make all the keys of reverse map unique.

因此,代碼可以正常運(yùn)行,但是反向鍵將刪除對4-> S100RR以使反向鍵的所有鍵都唯一。

翻譯自: https://www.includehelp.com/scala/reverse-keys-and-values-in-scala-map.aspx

scala中map添加值

總結(jié)

以上是生活随笔為你收集整理的scala中map添加值_如何在Scala Map中反转键和值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。