conditional expressions

Fernando Pérez fperez528 at yahoo.com
Fri Sep 27 21:55:07 EDT 2002


Mike Rovner 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)
>> 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.
>>
> 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])

Why not just a simple function?

In [23]: plur=lambda s,n:'%s %s' % (n,s+('','s')[n!=1])

In [24]: plur('cat',0)
Out[24]: '0 cats'

In [25]: plur('cat',1)
Out[25]: '1 cat'

In [26]: plur('cat',9)
Out[26]: '9 cats'

In [27]: na=1; np=3; nl=1; ng=0

In [28]: print "Found %s, %s, %s, %s" % (plur('apple',na),plur('plum',np),
   ....: plur('lemon',nl),plur('grape',ng))
Found 1 apple, 3 plums, 1 lemon, 0 grapes

If the list is big the above can easily be automated with a map or a list 
comprehension.

Cheers,

f.



More information about the Python-list mailing list