给定索引,如何从列表中返回多个项目? [英] How to return multiple items from a list, given their indices?

查看:43
本文介绍了给定索引,如何从列表中返回多个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say, I have a list. If I want to return something at the index of that list, I can just pass the lists' val, the index. Like so.

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

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

But what if I want items at multiple indexes on this list? I want to be able to do this... list(0, 1) and get a collection of the items at those indices.

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

This is crazily simple in Ruby. Anyone have any suggestions?

推荐答案

您可以翻转逻辑,这样对于每个索引,您都会获得索引,然后检索该索引处的元素.由于您在 List 上使用了 apply 方法,因此此逻辑有几个简写表达式:

You can flip the logic around, so that for each index, you're getting the index, you retrieve the element at that index. Since you are using the apply method on List, there are several shorthand expressions of this logic:

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

值得注意的是,由于这些都是indices上的maps,结果集合通常与indices具有相同的类型,而不是<代码>列表:

It's worth noting that since these are all maps on indices, the resulting collection will generally have the same type as indices, and not 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 中):

This can be an undesirable property here. One solution to this is to use breakOut (in scala.collection):

val newList: Array[Int] = indices.map(list)(breakOut)

您可以在此处阅读有关breakOut的更多信息.以下解决方案还通过对 list 而不是 indeces 执行操作,尽可能维护 list 的集合类型:

You can read more about breakOut here. The following solutions also maintain the collection type of list when possible by performing operations on list instead of indeces:

如果您正在寻找列表的连续范围,您可以考虑使用 slice:

If you are looking for a contiguous range of the list, you might consider using slice:

list.slice(1, 2) //List(2)

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

You could also use drop and take (and the dropRight, takeRight versions) to a similar effect:

list.drop(1).take(1)

对于此类过滤的更复杂版本,您可能对 zipWithIndex 方法感兴趣,它允许您在索引上表达任意逻辑:

For more complex versions of this type of filtering, you might be interested in the zipWithIndex method, which would allow you to express arbitrary logic on the index:

list.zipWithIndex.collect { 
    case(el, index) if indices.contains(index) /* any other logic */ => el 
}

这篇关于给定索引,如何从列表中返回多个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆