"v1", "k2" -> "v2", "k3" -> "v3", "k4" -> "v4", "k5" -> "v5", "k6" -> "v6", "k7" -> "-6ren">
gpt4 book ai didi

list - Scala:将 map 大小 n 拆分为列表( map 最大大小为 3)

转载 作者:行者123 更新时间:2023-12-05 01:12:40 27 4
gpt4 key购买 nike

在:

Map("k1" -> "v1", "k2" -> "v2", "k3" -> "v3", "k4" -> "v4", "k5" -> "v5", "k6" -> "v6", "k7" -> "v7", "k8" -> "v8", "k9" -> "v9", "k0" -> "v0")

输出:

List(Map("k1" -> "v1", "k2" -> "v2", "k3" -> "v3), Map("k4" -> "v4", "k5" -> "v5", "k6" -> "v6), Map("k7" -> "v7", "k8" -> "v8", "k9" -> "v9), Map("k0" -> "v0"))

最佳答案

val a = Map("k1" -> "v1", "k2" -> "v2", "k3" -> "v3", "k4" -> "v4", "k5" -> "v5", "k6" -> "v6", "k7" -> "v7", "k8" -> "v8", "k9" -> "v9", "k0" -> "v0")
a.grouped(3).toList

这给你:

res2: List[scala.collection.immutable.Map[String,String]] = List(Map(k2 -> v2, k0 -> v0, k5 -> v5), Map(k9 -> v9, k6 -> v6, k7 -> v7), Map(k1 -> v1, k4 -> v4, k3 -> v3), Map(k8 -> v8))

唯一没有订购

为了保持顺序你可以这样做:

a.toList.sortBy(_._1).grouped(3).toList.map(_.toMap)

这给了你:

res6: List[scala.collection.immutable.Map[String,String]] = List(Map(k0 -> v0, k1 -> v1, k2 -> v2), Map(k3 -> v3, k4 -> v4, k5 -> v5), Map(k6 -> v6, k7 -> v7, k8 -> v8), Map(k9 -> v9))

请注意,您的初始 Map 排序不正确(最后一个元素是“k0”,但它应该是第一个)。但是如果你想保持插入顺序并将 map 列表按 3 分组,这个应该可以工作:

val b = scala.collection.mutable.LinkedHashMap("k1" -> "v1", "k2" -> "v2", "k3" -> "v3", "k4" -> "v4", "k5" -> "v5", "k6" -> "v6", "k7" -> "v7", "k8" -> "v8", "k9" -> "v9", "k0" -> "v0")
b.toList.grouped(3).toList.map(_.toMap)

这导致:

res8: List[scala.collection.immutable.Map[String,String]] = List(Map(k1 -> v1, k2 -> v2, k3 -> v3), Map(k4 -> v4, k5 -> v5, k6 -> v6), Map(k7 -> v7, k8 -> v8, k9 -> v9), Map(k0 -> v0))

关于list - Scala:将 map 大小 n 拆分为列表( map 最大大小为 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22038135/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com