[Tutor] one line code
Pierre Barbier de Reuille
pierre.barbier at cirad.fr
Mon Apr 4 15:41:10 CEST 2005
Mmmhhh ... not strictly one line but ...
import re
float_str = re.compile(r"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$")
val = [ ( (float_str.match(s) and [float(s)]) or [s])[0] for s in l2 ]
It's not really "readable" but well ... it works ^_^
Pierre
Christian Meesters a écrit :
> Hi
>
> Yesterday night I was thinking about the following problem:
> I do have a list like l = ['1','2','3','abc','','4'] - for instance like
> a list one could get from a file import with the csv module (which is
> where my 'problem' comes from). Now I would like to generate the
> following list, preferably with one line of code:
> l2 = [1.0,2.0,3.0,'abc','',4.0]
> With other words I'd like to tell Python: Convert into a float if
> possible, otherwise append anyway. Is this possible in one line? (Right
> now my code is a lot longer.)
> I was trying with 'filter' + lambda forms, list comprehensions etc., but
> could not find a solution. Could it be that a C-like solution with '?'
> and ':' is more straightforward than a solution with Python or am I just
> too blind to see a real pythonic solution here?
>
> I am aware that putting a solution in one line of code might be against
> the 'Zen of Python' (... Complex is better than complicated ...
> Readability counts ...), but since I'm just asking out of curiosity,
> perhaps I'll get an answer anyway. ;-)
>
> Thanks a lot in advance.
> Cheers
> Christian
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
Pierre Barbier de Reuille
INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France
tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68
More information about the Tutor
mailing list