按项目索引过滤列表? [英] Filter a list by item index?

查看:40
本文介绍了按项目索引过滤列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

val data = List("foo", "bar", "bash")
val selection = List(0, 2)
val selectedData = data.filter(datum => selection.contains(datum.MYINDEX))
//                                                  INVALID CODE HERE ^
// selectedData: List("foo", "bash")

假设我想过滤一个 List 给定的选定索引列表.如果在 filter 方法中,我可以引用列表项的索引,那么我可以像上面那样解决这个问题,但是 datum.MYINDEX 在上述情况下无效.

Say I want to filter a List given a list of selected indices. If, in the filter method, I could reference the index of a list item then I could solve this as above, but datum.MYINDEX isn't valid in the above case.

我该怎么做?

推荐答案

如何使用 zipWithIndex 来保持对项目索引的引用,这样过滤,然后将索引映射掉?

How about using zipWithIndex to keep a reference to the item's index, filtering as such, then mapping the index away?

data.zipWithIndex
    .filter{ case (datum, index) => selection.contains(index) }
    .map(_._1)

这篇关于按项目索引过滤列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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