if the else short form
Mel
mwilson at the-wire.com
Wed Oct 6 20:44:52 EDT 2010
BartC wrote:
>
>
> "Lawrence D'Oliveiro" <ldo at geek-central.gen.new_zealand> wrote in message
> news:i8j0dg$lh7$2 at lust.ihug.co.nz...
>> In message <i8i1h8$dcl$1 at news.eternal-september.org>, BartC wrote:
>
>>> x = ("One","Two","Three") [i-1]
>>>
>>> While this works for i = 1,2,3, it goes funny for i=0,-1,-2, and
>>> generates
>>> an error for the rest ...
>>
>> x = {1 : "One", 2 : "Two", 3 : "Three"}.get(i, "None Of The Above")
>
> Yes, I expected Python to come up with something (it always does).
>
> However, as I mentioned, one problem here is having to evaluate all the
> items in the list before selecting one:
>
> def fna():
> print "FNA CALLED"
> return "One"
> def fnb():
> print "FNB CALLED"
> return "Two"
> def fnc():
> print "FNC CALLED"
> return "Three"
>
> i=16
> x = {1 : fna(), 2 : fnb(), 3 : fnc()}.get(i, "None Of The Above")
> print x
>
> Other than efficiency concerns, sometimes you don't want the extra
> side-effects.
>
> Probably there are workarounds here too,
The workaround would be (untested)
x = {1: fna, 2: fnb, 3: fnc}.get(i, lambda: "None Of The Above") ()
Mel.
More information about the Python-list
mailing list