Conditional Expression
I am fairly familiar with C, but new to Python. Does Python have something like the handy C conditional expression? For example:
// C conditional expression x = a ? b : c;
// if a is true then x = b else x = c
// here used to print 10 numbers in each row
// the numbers are separated by tabs, each row ends with a '\n'
#include <stdio.h>
int main()
{
int k;
for(k = 0; k < 100; k++)
{
printf("%3d%c", k, (k % 10 == 9) ? '\n' : '\t');
}
getchar(); // make the console wait
return 0;
}
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
Python lambda can substitute, just harder to read:
tuple1 = ('\t', '\n')
for k in range(100):
a = (k % 10 == 9)
b = 1
c = 0
# similar to C conditional expression a ? b : c
# if a is true return b else c
f = lambda a, b, c: (a and [b] or [c])[0]
print "%3d%s" % (k, tuple1[f(a, b, c)]),
bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
Bumsfeld, this is an interesting application of the lambda function!
You can even make it simpler using tuple indexing directly ...
for k in range(100):
# selects index 0 (False) or 1 (True) of tuple depending on == compare
select_tab_or_newline = ('\t', '\n')[k % 10 == 9]
print "%3d%s" % (k, select_tab_or_newline),
... or cut out the descriptive middleman ...
for k in range(100):
print "%3d%s" % (k, ('\t', '\n')[k % 10 == 9]),
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
Thank you all,
I will be trying all suggestions after I download version 2.5, to see which one I am most comfortable with.
Tuple indexing looks much like C, but then one should not copy C style into Python.
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213