def fun(x):
for k in range(10):
found = False
if x < 12 and other(k):
dostuff()
found = True
if x == 4 and other2(k):
dostuff()
found = True
if not found:
dootherstuff(k)
我有这个密码。我的问题是,既然x不变,这些if语句是否可以预先计算
代码应执行以下操作:
def fun(x):
if x == 4:
for k in range(10):
if other2(k):
dostuff()
else:
dootherstuff(k)
if x < 12:
for k in range(10):
if other(k):
dostuff()
else:
dootherstuff(k)
或者
def fun(x):
for k in range(10):
if x == 4 and other2(k) or x < 10 and other(k):
dostuff()
else:
dootherstuff(k)
但由于这两个都非常不干燥和丑陋,我想知道是否有更好的选择。在我的实际代码中,我有更多的语句,但我所需要的只是对X的某些值在循环中进行特定的检查,我不想在每次迭代中都检查X,因为它不会改变
您可以执行以下操作
我认为这应该是一样的:
相关问题 更多 >
编程相关推荐