Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most Pythonic way to filter a set?

Tags:

I have list consisting with replacements and I want to do two things:

  1. remove duplicates
  2. remove all elements by a specific criteria, to be exact I want to remove all elements bigger than a certain value.

I figured I can use filter for 2 and than use set to achieve 1 something like

list(set(filter(lambda x:x<C, l)))

is there a better/more pythonic/more efficient way?

like image 223
Meni Avatar asked Nov 26 '15 17:11

Meni


People also ask

Is filter a Pythonic?

Filter() is a built-in function in Python.

Can you filter a set 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.

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 names in Python?

Filter a list of string using filter() method. filter() method accepts two parameters. The first parameter takes a function name or None and the second parameter takes the name of the list variable as values. filter() method stores those data from the list if it returns true, otherwise, it discards the data.


2 Answers

Using list comprehension is maybe more "pythonic".

filtered = [x for x in set(lst) if x < C]
like image 62
Delgan Avatar answered Oct 19 '22 02:10

Delgan


The best two ways to do them are filter:

new_list = list(set(filter(lambda x:x<C, l)))

Or set comprehensions (which many would consider more pythonic, and even more efficient):

list({x for x in l if x < C})

But I guess, if you’re familiar with filter, that you can just stick to it.

like image 24
Y2H Avatar answered Oct 19 '22 01:10

Y2H