我想知道是否可以对嵌套在一个主语句下的 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/