[Tutor] how does this list comprehension work?
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Wed Mar 8 19:33:16 CET 2006
On Wed, 8 Mar 2006, Christopher Spears wrote:
> I copied this program from Learning Python and got it to work on Windows
> XP:
>
> import sys, glob
> print sys.argv[1:]
> sys.argv = [item for arg in sys.argv for item in
> glob.glob(arg)]
> print sys.argv[1:]
>
> The key to the script is the list comprehension, which I am having
> trouble dissecting. How do I go about trying to figure out how it
> works?
Hi Chris,
Hmmm. Let me stare at it again.
> sys.argv = [item for arg in sys.argv for item in
> glob.glob(arg)]
... Yikes. to tell the truth, I can't read this either.
But it might help if we translated it as this:
######
expandedArguments = []
for arg in sys.argv:
for item in glob.glob(arg):
expandedArguments.append(item)
######
Does this code make more sense?
But I'm not so sure myself that list comprehensions are so good when they
get so deeply nested; the nested structure is deceptively obscured in the
flatness of that list comprehension.
I would have just written the code above instead. Actually, I'd write a
function to capture that abstraction of a mapping and appending function.
Let's call it "mappend()":
##########################################################################
def mappend(f, L):
"""mappend applies f to each elements in L, and assumes that f returns
a list. It collects those results in a single flattened list."""
results = []
for x in L:
results.extend(f(x))
return results
##########################################################################
(The function name is common to folks who've done Lispy kinds of coding.)
And we can see this mappend() function in action:
######
>>> import glob
>>> mappend(glob.glob, ['*.txt', '*.doc'])
['sequences.txt', 'foo.txt', 'pub2ara-pipeline_20060216.doc',
'Admission Conditions.doc', 'PhD Offer.doc']
######
If you have more questions, please feel free to ask. Good luck!
More information about the Tutor
mailing list