Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a list of tuples

Tags:

list

filter

scala

I have a list of tuples and I want to filter out the all elements where the second value in the tuple is not equal to 7.

I do:

valuesAsList.filter(x=>x._2 != 7)

Can I use wildcard notation to make this even shorter?

Thanks.

like image 354
More Than Five Avatar asked May 08 '13 20:05

More Than Five


People also ask

How do you filter items in a list in Python?

Python has a built-in function called filter() that allows you to filter a list (or a tuple) in a more beautiful way. The filter() function iterates over the elements of the list and applies the fn() function to each element. It returns an iterator for the elements where the fn() returns True .

How do you filter a list of strings in Python?

filter() method is a very useful method of Python. One or more data values can be filtered from any string or list or dictionary in Python by using filter() method. It filters data based on any particular condition. It stores data when the condition returns true and discard data when returns false.

How do you filter a list?

Select a cell in the data table. On the Data tab of the Ribbon, in the Sort & Filter group, click Advanced, to open the Advanced Filter dialog box. For Action, select Filter the list, in-place.

How do you filter an array of objects in Python?

You can select attributes of a class using the dot notation. Suppose arr is an array of ProjectFile objects. Now you filter for SomeCocoapod using. NB: This returns a filter object, which is a generator.


2 Answers

You can

valuesAsList.filter(_._2 != 7)

But I doubt it should be preferred over your example or this (think readability):

valuesAsList.filter {case (_, v) => v != 7}
like image 68
om-nom-nom Avatar answered Sep 28 '22 07:09

om-nom-nom


Fairly straight forward, with no real advantage IMHO:

valuesAsList.filter(_._2 != 7)
like image 42
Richard Sitze Avatar answered Sep 28 '22 07:09

Richard Sitze