Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

scala - 如何替换地图中的重复键(How to replace duplicate keys in a map)

HI I am fairly new to scala programming.

(嗨,我对scala编程还很陌生。)

I want to know is there a way to rename the duplicate keys of map.

(我想知道是否有一种方法可以重命名map的重复键。)

Suppose if I have a scala map here like

(假设我在这里有一个斯卡拉地图)

("a"->1,"b"->2,"c"->3,"d"->4,"a"->5,"c"->6,"e"->7,"a"->8)

((“ a”-> 1,“ b”-> 2,“ c”-> 3,“ d”-> 4,“ a”-> 5,“ c”-> 6,“ e”-> 7, “ a”-> 8))

I want the output in below format.The map should look like

(我想要以下格式的输出。地图应该看起来像)

("a_1"->1,"b"->2,"c_1"->3,"d"->4,"a_2"->5,"c_2"->6,"e"->7,"a_3"->8)

((“ a_1”-> 1,“ b”-> 2,“ c_1”-> 3,“ d”-> 4,“ a_2”-> 5,“ c_2”-> 6,“ e”-> 7, “ a_3”-> 8))

I just want to kind of assign a count system for each duplicate key occurrance.

(我只想为每个重复的键出现分配一个计数系统。)

So far I have been able to write a code which will give the no of occurance for a duplicate key.

(到目前为止,我已经能够编写代码,避免重复密钥的出现。)

var seq=map.toSeq
var cnt=seq.groupBy(_._1).mapValues(_.length)`
  ask by Nils translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try the following :

(您可以尝试以下方法:)

val seq = Seq("a"->1,"b"->2,"c"->3,"d"->4,"a"->5,"c"->6,"e"->7,"a"->8)

val cnt = seq.groupBy(_._1).flatMap{case (_, elems) => elems.zipWithIndex.map{case ((k,v), i) => s"${k}_${i+1}" -> v}}
print(cnt)

Output :

(输出:)

Map(c_1 -> 3, d_1 -> 4, a_2 -> 5, b_1 -> 2, a_3 -> 8, c_2 -> 6, a_1 -> 1, e_1 -> 7)

Note : if " b_1 " should be formatted as " b ", you can introduce a condition based on elems size

(注意:如果将“ b_1 ”格式化为“ b ”,则可以根据elems大小引入条件)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...