opening more than 1 file

Andrew M. Kuchling akuchlin at cnri.reston.va.us
Fri Apr 23 09:59:20 EDT 1999


Gornauth writes:
>>files = map(lambda i: open("file%02d"%i, 'w'), range(N))
>
>I'm not completely sure how that one-liner works. To be honest, I have no
>clue whatsoever.

It would be equally workable to just use a for loop:

files = []
for i in range(N):
    files.append( open("file%02d"%i, 'w') )

Using map() is tricky, but lets you keep the line count down;
generally one shouldn't care too much about line count. :)
Take it step by step:

	* What does range(N) do?  It returns a list containing the
numbers 0,1,2, ... that are less than N.  range(5) returns [0, 1, 2,
3, 4].

	* What does map() do?  map(F, L), where F is some function and
L is some list (actually, any sequence type) returns a new list
containing the result of F applied to each element of L.  

map(F, range(N)) returns [ F(0), F(1), ... F(N-1) ].
map(string.upper, ["This", "is", "a", "test"] )  returns 
['THIS', 'IS', 'A', 'TEST']

	* What does lambda do?  It defines a function which doesn't
have a name (it's an anonymous function), and can only contain an
expression whose value is returned.  It's possible to assign the
anonymous function to a name, and it will act like any other Python
function.

>>>f = lambda x: x+1
>>> f(0)
1
>>> f(3)
4

	However, to define a named function it's clearer to just use
def f(x): return x+1 .  lambda is therefore usually used with map()
and its cousins filter() and reduce(), where you often need a function
which does something simple.   In that case, the function is only
needed for that one map(), so people are reluctant to write:

def opener(i): return open("file%02d"%i, 'w')
files = map(opener, range(N) )

The above two lines are equivalent to the one-liner using lambda; the
only difference is that now there's an opener() function lying around
in the namespace.

-- 
A.M. Kuchling			http://starship.python.net/crew/amk/
... but whenever optimization comes up, people get sucked into debates about
exciting but elaborate schemes not a one of which ever gets implemented;
better to get an easy 2% today than dream about 100% forever.
    -- Tim Peters, 22 Mar 1998





More information about the Python-list mailing list