Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a list by item index?

Tags:

scala

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")

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.

How could I do this instead?

like image 904
Cory Klein Avatar asked Sep 02 '14 19:09

Cory Klein


People also ask

How do you find the index of an element in a list of lists?

To find the (row, column) index pair of an element in a list of lists, iterate over the rows and their indices using the enumerate() function and use the row. index(x) method to determine the index of element x in the row .

How do you filter a list in a list Python?

Short answer: To filter a list of lists for a condition on the inner lists, use the list comprehension statement [x for x in list if condition(x)] and replace condition(x) with your filtering condition that returns True to include inner list x , and False otherwise.

How do you filter a list?

Select the data that you want to filterOn the Data tab, in the Sort & Filter group, click Filter. in the column header to display a list in which you can make filter choices. Note Depending on the type of data in the column, Microsoft Excel displays either Number Filters or Text Filters in the list.

What is the index of an item in a list?

Given lists are an ordered collection of items, each element has its unique position, and each element can be accessed by telling Python the position. These positions are called indexes. Index in a list starts with 0.


2 Answers

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)
like image 165
Michael Zajac Avatar answered Sep 18 '22 10:09

Michael Zajac


It's neater to do it the other way about (although potentially slow with Lists as indexing is slow (O(n)). Vectors would be better. On the other hand, the contains of the other solution for every item in data isn't exactly fast)

val data = List("foo", "bar", "bash")
         //> data  : List[String] = List(foo, bar, bash)
val selection = List(0, 2)  
         //> selection  : List[Int] = List(0, 2)
selection.map(index=>data(index))
         //> res0: List[String] = List(foo, bash)
like image 41
The Archetypal Paul Avatar answered Sep 19 '22 10:09

The Archetypal Paul