Christian Meesters wrote:
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.)

Well, not really in one line, but one function & one line: def f(x): try: return float(x) except ValueError: return x

l2 = [f(x) for x in l]

(I could imagine some obfuscated one-line LC using sting.digits an "or", but that will look too much like Perl ;-))

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

HTH,
Wolfram

_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to