gpt4 book ai didi

scala - 给定索引,如何从列表中返回多个项目?

转载 作者:行者123 更新时间:2023-12-01 07:18:18 28 4
gpt4 key购买 nike

比方说,我有一个 list 。如果我想在该列表的索引处返回某些内容,我可以只传递列表的 val,即索引。像这样。

val list = List(1, 2, 3) 
list(0) //Int = 1

但是如果我想要这个列表中多个索引的项目怎么办?我希望能够做到这一点... list(0, 1)并获取这些索引处的项目集合。

这在 Ruby 中非常简单。有人有什么建议吗?

最佳答案

您可以翻转逻辑,以便为每个索引获取索引,然后检索该索引处的元素。由于您使用的是 apply方法在 List ,这个逻辑有几种速记表达式:

val indices = List(0, 1)
indices.map(index => list.apply(index))
indices.map(index => list(index))
indices.map(list(_))
indices.map(list)
indices map list

值得注意的是,由于这些都是 mapsindices ,生成的集合通常与 indices 具有相同的类型,而不是 list :
val list = Array(1, 2, 3)
val indices = List(0, 1)
indices map list //List(1, 2), instead of Array(1, 2)

这在这里可能是一个不受欢迎的属性。对此的一种解决方案是使用 breakOut (在 scala.collection 中):
val newList: Array[Int] = indices.map(list)(breakOut)

你可以阅读更多关于 breakOut here .以下解决方案也维护了 list 的集合类型在可能的情况下通过对 list 执行操作而不是 indeces :

如果您正在寻找列表的连续范围,您可以考虑使用 slice :
list.slice(1, 2) //List(2)

您也可以使用 droptake (以及 dropRighttakeRight 版本)达到类似的效果:
list.drop(1).take(1)

对于此类过滤的更复杂版本,您可能对 zipWithIndex 感兴趣。方法,这将允许您在索引上表达任意逻辑:
list.zipWithIndex.collect { 
case(el, index) if indices.contains(index) /* any other logic */ => el
}

关于scala - 给定索引,如何从列表中返回多个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30878607/

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