Python在循环前评估ifs

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,因为它不会改变。


慕仙森
浏览 129回答 2
2回答

料青山看我应如是

认为这应该工作相同:&nbsp;def fun(x):&nbsp; &nbsp; for k in range(10);&nbsp; &nbsp; &nbsp; &nbsp; if x < 12 and other(k):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;dostuff()&nbsp; &nbsp; &nbsp; &nbsp; elif x == 4 and other2(k):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;dostuff()&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;dootherstuff(k)

SMILET

您可以执行以下操作def fun(x):&nbsp; &nbsp; cond1 = x < 12&nbsp; &nbsp; cond2 = x == 4&nbsp; &nbsp; for k in range(10):&nbsp; &nbsp; &nbsp; &nbsp; found = False&nbsp; &nbsp; &nbsp; &nbsp; if cond1 and other(k):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dostuff()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; found = True&nbsp; &nbsp; &nbsp; &nbsp; if cond2 and other2(k):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dostuff()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; found = True&nbsp; &nbsp; &nbsp; &nbsp; if not found:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dootherstuff(k)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python