A REALLY COOL PYTHON FEATURE:

Robert Citek rwcitek at uci.edu
Tue May 16 04:02:10 EDT 2000


At 11:20 PM 5/11/00 GMT, Ben Wolfson wrote:
>On 11 May 2000 11:56:59 GMT, m.faassen at vet.uu.nl (Martijn Faassen)
>wrote:
>
>>Courageous <jkraska1 at san.rr.com> wrote:
>>> reduce ( lambda x, y: x+", "+y, somenames )
>>
>>It's actually pretty easy in Python, too. :) (you think all this
>>reducing and lambda-ing is *easy*?)
>>
>>import string
>>string.join(["foo", "bar", "baz"], ", ")
>
>or:
>
>', '.join(['foo', 'bar', 'baz'])
>
>which is much less intuitive.


The join method is fine for converting lists to strings, but doesn't work
for converting lists to tuples.  However, lambda works nicely here:

reduce(lambda x, y: x + (y,), somenames, ())

Or in a practical example:

import sys, string
fmt = "%-20s %-20s %-20s"
for line in sys.stdin.readlines():
  print fmt % reduce(lambda x, y: x + (y,), string.split(line), ())

This will read a file containing exactly three fields from standard input
and print the fields using the format in fmt.  This works because
string.split returns a list which the reduce function converts to a tuple
for use by the print command.  BTW, this is only practical for small lists. :)

- Robert





More information about the Python-list mailing list