[英]What is the most Pythonic way to filter a set?
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 我想我可以使用filter for 2而不是使用set来实现1之类的东西
list(set(filter(lambda x:x<C, l)))
is there a better/more pythonic/more efficient way? 是否有更好/更pythonic /更有效的方式?
使用列表理解可能更“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): 或设置理解(许多人会考虑更多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. 但我想,如果你熟悉过滤器,你可以坚持下去。
In my opinion the most Pythonic way to filter sets, wheevern possible, is by use set operations (Venn diagrams) : 在我看来,尽管可能,过滤集的最Pythonic方法是使用set操作(维恩图):
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时,只需键入:
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. 并且在这个问题中,如果你需要过滤除C之外的更大的值,你只需在Python代码中输入“包含检查”操作符“in”。 contains () magic method (magic method shouldn't be called directly that's why you use "in"): contains ()魔术方法(不应该直接调用魔术方法,这就是你使用“in”的原因):
{x for x in l if x > C}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.