What is the most Pythonic way to filter a set?

2020-02-11 21:03发布

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?

3条回答
forever°为你锁心
2楼-- · 2020-02-11 21:33

In my opinion the most Pythonic way to filter sets, wheevern possible, is by 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 value 5 from set A you just type:

A - {5,}

and as in this question if you need to filter for grater values than C you just type "containment check" operator "in" which in Python code executes sets.contains() magic method (magic method shouldn't be called directly that's why you use "in"):

{x for x in l if x > C}
查看更多
混吃等死
3楼-- · 2020-02-11 21:54

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.

查看更多
Evening l夕情丶
4楼-- · 2020-02-11 21:57

Using list comprehension is maybe more "pythonic".

filtered = [x for x in set(lst) if x < C]
查看更多
登录 后发表回答