python - 具有优先级/顺序的循环

标签 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

最佳答案

情况已经如此:

if True:
    print(1)

if True:
    print(2)

if False:
    print(3)

if True:
    print(4)

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

如果您只想打印 1,请使用 elif(else 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

关于python - 具有优先级/顺序的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25927310/

相关文章:

python - 为什么在 sqlalchemy 中同时更新同一条记录不会失败?

python - numpy 或 scipy 有哪些可能的计算可以返回 NaN?

swift - 使用循环从 plist 的根级别获取字典数组并将其放入变量中

javascript - 向表中添加行、循环数组、做疯狂的事情、每次读取第一行

loops - 为什么这个 IF 语句不需要 End IF

Python属性错误: 'Series' object has no attribute 'isdigit'

python - Tensorflow 中的正确批量归一化功能是什么?

c++ - 查找文件中 10 个最长的单词

sql - 如何在 ORACLE 上传递计数作为 IF 条件

PHP 如果简写并在一行中回显 - 可能吗?