conditional expressions
Bengt Richter
bokr at oz.net
Sat Sep 28 11:57:27 EDT 2002
On Fri, 27 Sep 2002 15:24:04 -0700, "Mike Rovner" <mike at bindkey.com> wrote:
>
>"Terry Reedy" <tjreedy at udel.edu> wrote in message
>news:t_3l9.334924$AR1.14880141 at bin2.nnrp.aus1.giganews.com...
>> na=1; np=3; nl=1; ng=0
>> print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\
>> (na, na!=1 and 's' or '', np, np!=1 and 's' or '', nl, nl!=1 and 's'
>> or '', ng, ng!=1 and 's' or '')
>>
>> Found: 1 apple, 3 plums, 1 lemon, and 0 grapes.
>>
>> Alternatives to this 'risky' construct:
>> 1. forgo the nicety of correct English output
>> 2. nest if/else four levels deep to choose correct variant of 16 print
>> statements (ugh)
or just generate the correct variant:
fmt = "Found: %%d apple%s, %%d plum%s, %%d lemon%s, and %%d grape%s." % \
tuple([('','s')[x!=1] for x in [na,np,nl,ng]])
print fmt % (na, np, nl, ng)
or pre-generate all sixteen:
>>> fmtList=["Found: %%d apple%s, %%d plum%s, %%d lemon%s, and %%d grape%s." % (a,p,l,g)
... for a in ('','s') for p in ('','s') for l in ('','s') for g in ('','s') ]
and select the correct one by index:
>>> fmt = fmtList[(na!=1)*8+(np!=1)*4+(nl!=1)*2+(ng!=1)]
>>> print fmt % (na, np, nl, ng)
Found: 1 apple, 3 plums, 1 lemon, and 0 grapes.
>> 3. precalculate 4 suffixes and store in 4 temp vars with 4 if/else's
>> (8 or 16 lines);
>> though clearly superiour to 2), this is still tedious with some
>> risk of typo error.
Why so many lines? If you really want the temps:
tmpa, tmpp, tmpl, tmpg = [('','s')[x!=1] for x in [na,np,nl,ng]]
or
tmpa, tmpp, tmpl, tmpg = map(lambda x:'s'[x==1:], [na,np,nl,ng])
>>
>4. Try:
>use_s=('','s')
>print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\
>(na, use_s[na!=1], np, use_s[np!=1], nl, use_s[nl!=1], ng, use_s[ng!=1])
>
5.:
>>> na=1; np=3; nl=1; ng=0
>>> def s(n): return 's'[n==1:]
...
>>> print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." % (
... na, s(na), np, s(np), nl, s(nl), ng, s(ng)
... )
Found: 1 apple, 3 plums, 1 lemon, and 0 grapes.
6.:
>>> class NQ:
... def __init__(self, name, quant):
... self.name = name
... self.quant = quant
... def __str__(self):
... return '%s %s%s' % (self.quant, self.name, ('', 's')[self.quant!=1])
...
>>> print "Found: %s, %s, %s, and %s." % (
... NQ('apple',na), NQ('plum',np), NQ('lemon',nl), NQ('grape',ng)
... )
Found: 1 apple, 3 plums, 1 lemon, and 0 grapes.
7.:
>>> print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." % \
... tuple([[x, x!=1 and 's' or ''][y] for x in [na,np,nl,ng] for y in [0,1]])
Found: 1 apple, 3 plums, 1 lemon, and 0 grapes.
... ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list