Integer From A Float List?!?

Nick Coghlan ncoghlan at iinet.net.au
Sat Mar 5 04:54:53 CET 2005


Bill Mill wrote:
> You're going to have to use loops. I don't know how Matlab can do it
> without them, unless it maintains the matrix as a list of floats and
> simply *views* it as a list of ints. More likely, it simply hides the
> loop away from you. Anyway, here's some ways to do it:
> 
> preferable: int_matrix = [int(x) for x in matrix]
> old way: int_matrix = map(int, matrix)
> explicit:
> int_matrix = []
> for x in matrix:
>     int_matrix.append(int(x))
> 

C:\>python -m timeit -s "floats = map(float, range(1000))" "ints = map(int, floa
ts)"
1000 loops, best of 3: 481 usec per loop

C:\>python -m timeit -s "floats = map(float, range(1000))" "ints = [int(x) for x
  in floats]"
1000 loops, best of 3: 721 usec per loop

C:\>python -m timeit -s "floats = map(float, range(1000))" "ints = []" "for x in
  floats: ints.append(int(x))"
1000 loops, best of 3: 992 usec per loop

For builtin functions, map is usually the fastest option (and, IMO, the most 
readable). List comprehensions should be preferred to map + lambda, though.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list