我想知道是否可以优先处理嵌套在一个主要语句下的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
答案 0 :(得分:2)
情况已经如此:
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
答案 1 :(得分:1)
您应该使用if-elif
,这相当于switch-case
语句,就像它已完成here