I have list consisting with replacements and I want to do two things:
我有包含替换的列表,我想做两件事:
- remove duplicates
- 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
我想我可以使用2的过滤器,而不是使用set来实现1之类的东西
list(set(filter(lambda x:x<C, l)))
is there a better/more pythonic/more efficient way?
是否有更好/更pythonic /更有效的方式?
2 个解决方案
#1
11
Using list comprehension is maybe more "pythonic".
使用列表理解可能更“pythonic”。
filtered = [x for x in set(lst) if x < C]
#2
3
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):
或设置理解(许多人会考虑更多pythonic,甚至更有效):
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.
但我想,如果你熟悉过滤器,你可以坚持下去。
#1
11
Using list comprehension is maybe more "pythonic".
使用列表理解可能更“pythonic”。
filtered = [x for x in set(lst) if x < C]
#2
3
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):
或设置理解(许多人会考虑更多pythonic,甚至更有效):
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.
但我想,如果你熟悉过滤器,你可以坚持下去。