使用map将Map("a"

编程入门 行业动态 更新时间:2024-10-28 06:35:25
本文介绍了使用map将Map("a"-> 2,"b"-> 1)转换为seq("a","a","b")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试通过地图将Map("a"-> 2,"b"-> 1)转换为seq("a","a","b")函数,目前我正在尝试运行下面的代码,以提供所需的结果.

I am trying to turn a Map("a" -> 2, "b" -> 1) into seq("a","a","b") through the map function, Currently I am trying to run the code below giving me the desired result.

是否有更聪明的方法来做到这一点?可能是通过map函数更好的方法吗?

Is there a smarter way to do this? Possibly a better way through the map function?

var multiset : Seq[T] = Seq[T]() var variables : Seq[T] = data.map(x => x._1).toSeq var variableCounts : Seq[Int] = data.map(x => x._2).toSeq for(x <- 0 until variables.length){ for(y <- 0 until variableCounts(x)) multiset = multiset :+ variables(x) }

推荐答案

您可以执行以下操作: 从fill的定义中使用GenTraversableFactory def fill[A](n: Int)(elem: => A): CC[A]的fill方法,我们可以看到它需要一个整数和一个元素.整数告诉我们需要多少次填充给定的元素.

you can do something like this: Use fill method of GenTraversableFactory def fill[A](n: Int)(elem: => A): CC[A] from the definition of fill we can see that it takes an integer and an element. Integer tell how many times we need to fill the given element.

object Demo extends App { val x = Map("a" -> 2, "b" -> 1) val p: Seq[String] = x.flatMap { tuple => List.fill(tuple._2)(tuple._1) }.toSeq print(p) //output: List(a, a, b) }

我希望对您有帮助!

如果要避免使用tuple._1和tuple._1,可以使用以下方法.

If you want to avoid tuple._1 and tuple._1 you can use the following approach.

object Demo extends App { val x = Map("a" -> 2, "b" -> 1) val p: Seq[String] = x.flatMap { case (key, value) => List.fill(value)(key) }.toSeq print(p) //output: List(a, a, b) }

更多推荐

使用map将Map("a"

本文发布于:2023-11-25 05:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628439.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:map   Map   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!