I have list consisting with replacements and I want to do two things:
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?
Filter() is a built-in function 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.
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.
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.
Using list comprehension is maybe more "pythonic".
filtered = [x for x in set(lst) if x < C]
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.
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