imap and ifilter vs. generator comprehensions
I'm curious about the insignificant technical details -- differences between these two in python's internal representati开发者_运维知识库on, performance and stuff like that.
Generally, using map and filter is discouraged, but you are mapping-filtering by just one function, they are useful. But never use map or filter with lambda Consider this:
Places where filter or map is better:
(i for i in iterable if i), filter(bool, i)
(int(i) for i in iterable), map(int, i)
See, they are simplier. But, consider this:
(i+3 for i in iterable), map(lambda i: i+3, iterable)
(i for i in iterable if i.isdigit()), filter(lambda i, i.isdigit(), iterable)
And one advantage for generator expressions, you can mix map and filter functionality.
(f(i) for i in iterable if g(i)), map(f, filter(g, iterable))
For me the rules are:
- Never use lambda in map or filter.
- Only use map or filter if it's obvious what you are doing.
- For everything else, use generator expressions.
- If in doubt, use generator expressions.
Edit:
Forgot one important thing:
On Python versions older than 3, map(and filter) is eager, so it's better compare it with list comprehensions. But on Python 3, map is lazy, it acts like generator expressions.
加载中,请稍侯......
精彩评论