[CentralOH] 2016-10-14 道場 Scribbles 落書/惡文? Part Three: list builder/list comprehension/generator function/generator expression/functional/; readability and optimization; chapter 20 lp
jep200404 at columbus.rr.com
jep200404 at columbus.rr.com
Thu Oct 27 16:26:23 EDT 2016
Part Three:
The full version seems to have been caught in some filters,
so it is being reposted in smaller pieces.
common theme was converting list builder:
foo = []
for x in someiterable:
foo.append(goo(x))
return foo
to a comprehension
return [goo(x) for x in someiterable]
to a generator function
for x in someiterable:
yield goo(x)
or a generator expression
return (goo(x) for x in someiterable)
to a functional approach
return map(goo, someiterable)
which of the above is easier for you to read?
N = 4
def grok():
foo = []
for x in someiterable:
foo.append(goo(x))
return foo[N:]
def grok():
foo = (goo(x) for x in someiterable)
return itertools.islice(foo, N, None)
which grok is easier for you to grok?
which handles arbitrarily large someiterable??
Read Chapter 20 of Learning Python, 5th edition by Mark Lutz
code for readability first
tweak for speed only if needed
Premature optimization is the root of all evil.
wp:Premature_optimization#When_to_optimize
More information about the CentralOH
mailing list