[Tutor] Re: one line code
Andrei
project5 at redrival.net
Mon Apr 4 19:20:46 CEST 2005
Christian Meesters wrote on Mon, 4 Apr 2005 14:49:28 +0200:
<snip>
> 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?
Pierre did the Python equivalent of the ternary operator in his solution.
> 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. ;-)
>>> l = ['1','2','3','abc','','4', '9.5', 9]
>>> [(eval(compile('exec """try:t=float("%s")\nexcept:t="%s" """ in globals(),locals()'%(s,s),'','exec')),t)[1] for s in l]
[1.0, 2.0, 3.0, 'abc', '', 4.0, 9.5, 9.0]
I would recommend against it though :). Having a special function for this
purpose is the way to go, a ternary operator doesn't really add anything to
the quality of the code.
--
Yours,
Andrei
=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.
More information about the Tutor
mailing list