[Tutor] mapping/filtering a sequence
Mark Tolonen
metolone+gmane at gmail.com
Sat Sep 5 18:22:33 CEST 2009
"Douglas Philips" <dgou at mac.com> wrote in message
news:6A3250C7-31B6-4958-8E0A-F538989ED4F9 at mac.com...
> On or about 2009 Sep 5, at 10:45 AM, Martin A. Brown indited:
>> Have you discovered the map() builtin yet?
>>
>> I would imagine that others on this list will have some even more
>> elegant and efficient solutions for you, but here's a possibility:
>>
>> def filt_seq( thing ):
>> if thing == 38:
>> thing = thing - 4
>> elif thing == 40:
>> thing = thing - 1
>> return thing
>>
>> l = [ 1, 17, 12, 38, 4, 40, 17, 19 ]
>> l = map( filt_seq, l )
>>
>> Good luck,
>
>
> I must have missed a message or two, because I don't understand why math
> is being done on constants like that.
> Given my misunderstanding, I'd go with:
>
> my_map = { 38: 34, 40: 39 }
>
> def filter_item(item):
> return my_map.get(item, item)
>
> l = [ ... ]
> l = map(filter_item, l)
As a list comp:
>>> L=range(30,41)
>>> [{38:34,40:39}.get(n,n) for n in L]
[30, 31, 32, 33, 34, 35, 36, 37, 34, 39, 39]
-Mark
More information about the Tutor
mailing list