[Tutor] one line code
C Smith
smichr at hotmail.com
Tue Apr 5 07:45:08 CEST 2005
> From: "Alan Gauld" <alan.gauld at freenet.co.uk>
>
>> With other words I'd like to tell Python: Convert into a float if
>> possible, otherwise append anyway.
>
> [ (type(x) == type(5) and float(x) or x) for x in mylist ]
>
This is a perfect opportunity to give the reminder that the conversion
functions are also types that can be used more transparently for such
type tests:
###
>>> type(int)
<type 'type'>
>>> type(1)==int
True
>>> type(1)==float
False
###
If you really want a float and not an int then you should use the
following 1-liner as suggested by the programming FAQ 1.2.11 (
http://www.python.org/doc/faq/programming.html ):
[ (type(x) == int and [float(x)] or [x])[0] for x in mylist]
###
>>> l=['foo', 0]
>>> [(type(x)==int and float(x) or x) for x in l]
['foo', 0]
>>> # notice that 0 is still an int, not a float
>>> [(type(x)==int and [float(x)] or [x])[0] for x in l]
['foo', 0.0]
>>> # ok, that's better
###
/c
More information about the Tutor
mailing list