What is the most Pythonic filtering method of a kit?

I have a list consisting of replacements, and I want to do two things:

  • remove duplicates
  • delete all elements according to certain criteria, or rather, I want to delete all elements that exceed a certain value.

I figured I could use a filter for 2 and use a set to reach 1 something like

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

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

+12
source share
3 answers

Using list comprehension may be more "pythonic."

 filtered = [x for x in set(lst) if x < C] 
+19
source

The best two ways to do this is through a filter:

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

Or ask for an understanding (which many consider more pythonic and even more effective):

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

But I think if you are familiar with the filter, you can just stick with it.

+6
source

In my opinion, the most Pythonic way to filter sets where possible is to use set operations (Venn diagrams):

 A = {0, 1, 4, 5, 8}; B = {2, 1, 3, 4, 6}; print("Union :", A | B) print("Intersection :", A & B) print("Difference :", A - B) print("Symmetric difference :", A ^ B) 

Another example, when you just want to remove the value 5 from set A, simply type:

 A - {5,} 

and as in this question, if you need to filter for larger values ​​than C, you simply type the “content validation statement” into “in”, which sets up in Python code. the magic method contains () (the magic method should not be called directly, so you use the "in"):

 {x for x in l if x > C} 
0
source

Source: https://habr.com/ru/post/1236920/


All Articles