mapping a statement over all list items

Gerhard =?unknown-8bit?Q?H=E4ring?= gh_pythonlist at gmx.de
Sun Nov 11 04:29:02 EST 2001


On Sun, Nov 11, 2001 at 03:10:15AM -0600, Kevin Christie wrote:
> Hello all!
> 
>   I have list Foo, of strings. Each string has a special character '-' 
> within the string. What I want is for Python to split each string list 
> item by '-' and assign the resulting lists to the original list item.
> Basically, I want to apply:
> 
> Foo[x] = Foo[x].split('-')
> 
> over all items x in Foo, in one clean statement.
> 
> Thus if Foo was ['abc-xyz', 'black-blue', '123-987'], the result after 
> mapping to Foo would be:
> 
> Foo = [ ['abc', 'xyz'], ['black','blue'], ['123','987'] ]
> 
> It seems as if there should be a way to map the function over all items [...]
                                          ^^^
:-) Check out the map builtin in the documentation. Basically, the form is
map(function, sequence), like in:

import string
input = ['abc-xyz', 'black-blue']
result = map(lambda x, string.split(x, '-'), input)

Other tools for functional programming are lambda, apply, reduce and zip. Very
often, list comprehensions are easier to use and more readable than using map
and friends. For your example:

import string
input = ['abc-xyz', 'black-blue']
result = [string.split(x, '-') for x in input]

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))




More information about the Python-list mailing list