<p>建立一个操作列表并存储要处理的值。如果您想知道是否有任何计算大于0,请使用函数<code>any()</code></p>
<pre><code>x = 3
calculations = [x+1,x+2,x+(-3)]
if any(calculations):
#do something
print("there's something above 0")
</code></pre>
<p>如果您需要根据每个“函数”返回的值大于零来执行特定的计算,您可以将计算创建为函数,并创建一个字典,将结果作为值托管,函数名作为键(我们将计算的创建放在函数中,因为我们希望动态地获取值,而不是在字典已创建,因此我们每次都会根据传入的值创建一个新字典。这样你就知道哪一个返回什么值。如果要根据返回值大于0的内容进行处理,只需创建另一个字典并使用返回的键作为<code>to_do</code>字典的键:</p>
<pre><code>def aapl_calc(value):
return value + 5
def goo_calc(value):
return value -2
def calculate_everything(x):
return {"aapl":aapl_calc(x), "goo":goo_calc(x)}
def appl_to_do():
print("appl was greater than zero")
def goo_to_do():
print("goo was greater than zero")
to_do = {"aapl": appl_to_do, "goo":goo_to_do}
results = calculate_everything(2)
#checking if anything is greater than zero is easy
if any(results.values()):
print("something return as 0")
#creating a list of greater than 0 to use as keys
greater_than_zero = [key for key, val in results.items() if val]
#run each of the values greater than 0
for each in greater_than_zero:
to_do[each]()
</code></pre>
<p>但是<code>if</code>语句没有什么错,读起来更干净。你知道吗</p>