gpt4 book ai didi

scala - 如何让元素包含 '$'字符作为key,并把key后面的数字作为List?

转载 作者:行者123 更新时间:2023-12-04 17:21:18 24 4
gpt4 key购买 nike

有一个Array,如何让元素中包含'$'字符作为key,并在key后面的数字作为List

val a = Array("$A", 1234, "$B", 123, 4, 5)

预期:

Map("$A"->List(1234),"$B"->List(123,4,5)))

谢谢所有回答者,下面是我的最终代码:

a.toList.tails.collect {
case (key: String) :: rest if key.contains('$') => (key, rest.takeWhile(!_.toString.contains('$')))
}.toMap

最佳答案

您可以使用 foldLeft 来完成此操作(假设 Array[Any] 作为输入):

a.foldLeft(List.empty[(String, List[Int])]){
case (acc, el: String) if el.head == '$' =>
(el -> List.empty[Int]) :: acc
case (acc, el) =>
val updatedHead = acc.head._1 -> (Integer.parseInt(el.toString) :: acc.head._2)
updatedHead :: acc.tail
}.toMap.mapValues(_.reverse)
需要

reverse ,因为 :: (将元素添加到列表的开头)比将元素添加到末尾更快,但是 List[Int] 以这种方式反转。

另一个选项是尾递归调用 span .

附注请注意,Map 不保证插入顺序(即使对于键,无论它是迭代器),因此您不能将其用于累加器(您无法获取 keys.last 元素):

scala> (1 to 10).toList.foldLeft(Map.empty[Int, Int]){case (acc, x) => acc + (x -> x)}.keys.toList
res23: List[Int] = List(5, 10, 1, 6, 9, 2, 7, 3, 8, 4)

但是,您可以使用ListMap,但keys.lastlist.head(恒定时间)慢(线性时间)。

P.S.2 请记住,您的 a.toList.tails.collect... 版本会重新访问某些元素 2-3 次:当collect跳过整数时额外增加1次,当takeWhile检测到时额外增加1次序列结束,因此可能会影响性能。

关于scala - 如何让元素包含 '$'字符作为key,并把key后面的数字作为List?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45011593/

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