[Tutor] one line code

Christian Meesters meesters at uni-mainz.de
Mon Apr 4 14:49:28 CEST 2005


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.

More information about the Tutor mailing list