条件演算子の記述法

メモ。
こう書く必要があると。

(condition and [value_when_true] or [value_when_false])[0]

初めてのPythonでよくわからないとこ - テックノート@ama-ch




>>> (t and f) or y
99
>>> ((t and [f]) or [y])[0]
0

?: - Wikipedia, the free encyclopedia


The Python programming language uses a different syntax for this operator:

value_when_true if condition else value_when_false

This feature is not available for Python versions prior to 2.5, however. The Python programming FAQ mentions several possible workarounds for these versions, with varying degrees of simplicity versus semantic exactness (for example, regarding the short-circuit evaluation property of ?:). The most complete alternative, that has all the same properties as ?: and still works in Python versions prior to 2.5, would be:

(condition and [value_when_true] or [value_when_false])[0]

Note that value_when_true and value_when_false must be put in lists, because the expression would otherwise return value_when_false if value_when_true evaluated to False.