<p>我在一个关于<a href="https://stackoverflow.com/a/3421173/343215">knapsack problems</a>的问题中遇到了这个表达式:</p>
<pre><code>def f(v, i, S):
if i >= len(v): return 1 if S == 0 else 0
count = f(v, i + 1, S)
count += f(v, i + 1, S - v[i])
return count
</code></pre>
<p>当我试图用更一般的形式写出第二行<code>if i >= len(v): return 1 if S == 0 else 0</code>时,我得到一个错误:</strike></p>
^{pr2}$
<p>在
下面是一个广义形式:</p>
<pre><code>In [16]: if True : print("first") if True else print("second")
first
In [17]: if True : print("first") if False else print("second")
second
In [18]: if False : print("first") if True else print("second")
[nothing]
In [19]: if False : print("first") if False else print("second")
[nothing]
</code></pre>
<p>这叫什么?在</p>
<p>我很惊讶你能去掉<code>if...then...else</code>的第二个正例,然后把它变成<code>if...else</code>。在</p>
<hr/>
<p><strong>更新:关于python3 noob的错误,我只是没注意。如前所述,如果没有错误,答案就没有意义,因此我删除了错误代码。</strong></p>