Convert '165.0' to int

Billy Mays noway at nohow.com
Sun Jul 24 20:07:09 EDT 2011


On 7/24/2011 2:27 PM, SigmundV wrote:
> On Jul 21, 10:31 am, "Frank Millman"<fr... at chagford.com>  wrote:
>> Is there a short cut, or must I do this every time (I have lots of them!) ?
>> I know I can write a function to do this, but is there anything built-in?
>
> I'd say that we have established that there is no shortcut, no built-
> in for this. You write you own function:
>
> string_to_int = lambda s: int(float(s))
>
> Then you apply it to your list of strings:
>
> list_of_integers = map(string_to_int, list_of_strings)
>
> Of course, this will be horribly slow if you have thousands of
> strings. In such a case you should use an iterator (assuming you use
> python 2.7):
>
> import itertools as it
> iterator = it.imap(string_to_int, list_of_strings)
>
>
> Regards,
>
> Sigmund

if the goal is speed, then you should use generator expressions:

list_of_integers = (int(float(s)) for s in list_of_strings)



More information about the Python-list mailing list