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?
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 .
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.
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.
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.
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'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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With