map in Python

Simon Brunning simon.brunning at gmail.com
Fri Jan 21 07:37:46 EST 2005


On 21 Jan 2005 04:25:27 -0800, Stu <stuart at zapata.org> wrote:
> I have recently switched over to Python from Perl. I want to do
> something like this in Python:
> 
> @test = ("a1", "a2", "a3");
> map {s/[a-z]//g} @test;
> print @test;
> 
> However, I take it there is no equivalent to $_ in Python. But in that
> case how does map pass the elements of a sequence to a function? I
> tried the following, but it doesn't work because the interpreter
> complains about a missing third argument to re.sub.
> 
> import re
> test = ["a1", "a2", "a3"]
> map(re.sub("[a-z]", ""), test)
> print test

This what you want?

>>> import re
>>> test = ["a1", "a2", "a3"]
>>> test = [re.sub("[a-z]", "", item) for item in test]
>>> test
['1', '2', '3']

-- 
Cheers,
Simon B,
simon at brunningonline.net,
http://www.brunningonline.net/simon/blog/



More information about the Python-list mailing list