[Tutor] Re: Split string and convert to int

Andrei project5 at redrival.net
Wed Oct 29 21:47:27 EST 2003


mlong at datalong.com wrote on Wed, 29 Oct 2003 21:25:19 -0500 (EST):

> Thanks for the responses. Having the example using map has helped me to
> finally understand what it does. I had read about the map function in the
> docs but did not fully get it until now. I would like a little more
> clarification however. Lloyd prefers using list comprehension and Karl
> prefers the map function. Is this difference due to personal preference,
> or are there some other technical reasons for using one over the other.

There are probably speed differences between the two, but nothing you'd
notice for such small amounts of numbers. I don't know which would be
fastest when used to convert many numbers. 
Another difference is that the map() solution requires less typing.
GvR (that's the guy who wrote/writes Python) prefers list comprehensions if
I'm not mistaken, so that makes them more pythonic :).

What it comes down to in this case is probably taste. I would take the
comprehension over the map because I like list comprehensions better than
map, but if this code needed good performance, I'd test the two solutions
and pick the fastest one.

Andrei

>> An unnamed person wrote:
>>
>>> I have a string variable that represents a date. I want to pull out the
>>> individual parts as integers. Is there a more efficient way to do this?
>>
>>> fooDate='10/3/2003'
>>
>>> month, day, year = fooDate.split('/')
>>> month=int(month)
>>> day=int(day)
>>> year=int(year)
>>
>> In [9]: fooDate='10/3/2003'
>>
>> In [10]: [month, day, year] = map(int, fooDate.split('/'))
>>
>> In [11]: #or
>>
>> In [12]: [month, day, year] = [int(x) for x in fooDate.split('/')]
>>
>>
>> But in that case I would prefer map.
>>
>>    Karl
>> --
>> Please do *not* send copies of replies to me.
>> I read the list




More information about the Tutor mailing list