Tuesday, March 14, 2006

Python note: "?:" in Python

In C++ and Java there is a handy way of writing conditional expression, such as x = y>1?1:0. However there is no ?: operator in Python.

Several ways have been suggested around this problem. Some people use "a and b or c", while others use "(a and [b] or [c])[0]". However I don't think them intuitive.

I was using dict for the expression, and to express x = y>1 ? 1 : 0, I type

x = {True : 1, False : 0}[y>1]

which is also concise.

No comments: