具有优先级/顺序的循环

时间:2014-09-19 05:59:12

标签: python loops if-statement

我想知道是否可以优先处理嵌套在一个主要语句下的if语句中的代码,如下所示:

for blah:
    if case1:
        # takes highest priority and
        # will execute first even if
        # other cases are true
    if case2:
        # takes lower priority
    if case3:
        # takes lowest priority

我唯一能找到的东西可能是heapq等优先级队列,但我不完全理解它们是如何工作的,或者它们是否相关。

更具体地说是我的代码:

for x in list_of_lists:    # x would be a list then containing multiple integers
    if 1 in x and not (2 in x or 3 in x):
        # basically just want to see if the list "x" = [1]
        # takes highest priority and
        # will execute first even if
        # other cases are true
    if 1 in x and (2 in x or 3 in x):
        # checking to see if the list "x" contains a 1 and a 2, or a 1 and a 3
        # takes lower priority
    if something similar to the above:
        # takes lowest priority

2 个答案:

答案 0 :(得分:2)

情况已经如此:

if True:
    print(1)

if True:
    print(2)

if False:
    print(3)

if True:
    print(4)

#>>> 1
#>>> 2
#>>> 4

如果您只想打印1,请使用elifelse if的缩写):

if True:
    print(1)

elif True:
    print(2)

elif False:
    print(3)

elif True:
    print(4)

#>>> 1

这与if...else的级联相同,因此else if收缩:

if True:
    print(1)

else:
    if True:
        print(2)

    else:
        if False:
            print(3)

        else:
            if True:
                print(4)

#>>> 1

答案 1 :(得分:1)

您应该使用if-elif,这相当于switch-case语句,就像它已完成here