我很難理解為什么我的腳本只匹配字典中的第一個鍵,而不繼續處理其他鍵。
如果說僅存在 tcp 埠,我的腳本會生成我需要的命令,但是如果我嘗試混合使用它并具有其他埠(鍵),它將不會處理其他 elif。無論我是否將其放入 for 回圈中,我似乎都得到了相同的結果。我是新手,所以我可能在這里錯過了一些基本的東西。
ports = {'tcp': [['10', '20']], 'rant': [['100', '200']], 'cm': ['https']}
if __name__ == "__main__":
obj = []
tcpport = []
udpport = []
mxport = []
if ports.get("tcp"):
tcp2 = ports.get("tcp")
tcpport = True
for t in compile_port2(tcp2):
obj.append(t)
print("compiled tcp only objects")
elif ports.get("udp"):
udpport = True
udp2 = ports.get("udp")
for u in compile_port2(udp2):
obj.append(u)
print("compiled udp only objects")
elif ports.get("rant"):
rant2 = ports.get("rant")
tcpport = True
ran_tcp2 = (list(it.zip_longest(*[iter(rant2[0])] * 2)))
for rt in compile_rant_port2(ran_tcp2):
obj.append(rt)
print("compiled tcp only range objects")
elif ports.get("ranu"):
ranu2 = ports.get("ranu")
udpport = True
ran_udp2 = (list(it.zip_longest(*[iter(ranu2[0])] * 2))) # split strings by groups of 2 for port ranges
for ru in compile_rant_port2(ran_udp2):
obj.append(ru)
print("compiled udp only range objects")
elif ports.get("cm"):
tcpport = True
cm2 = ports.get("cm")
for c in compile_port2(cm2):
obj.append(c)
print("compiled worded objects\n\n")
else:
print("no items found")
uj5u.com熱心網友回復:
的用途elif是評估else-if條件。因此,如果if條件匹配,它將不匹配任何其他elifs'。
如果你想處理所有的鍵,你應該多個if條件而不是elif.
見下,修改版
ports = {'tcp': [['10', '20']], 'rant': [['100', '200']], 'cm': ['https']}
if __name__ == "__main__":
obj = []
tcpport = []
udpport = []
mxport = []
items_found = False
if "tcp" in ports:
items_found=True
tcp2 = ports.get("tcp")
tcpport = True
for t in compile_port2(tcp2):
obj.append(t)
print("compiled tcp only objects")
if "udp" in ports:
items_found = True
udpport = True
udp2 = ports.get("udp")
for u in compile_port2(udp2):
obj.append(u)
print("compiled udp only objects")
if "rant" in ports:
items_found = True
rant2 = ports.get("rant")
tcpport = True
ran_tcp2 = (list(it.zip_longest(*[iter(rant2[0])] * 2)))
for rt in compile_rant_port2(ran_tcp2):
obj.append(rt)
print("compiled tcp only range objects")
if "ranu" in ports:
items_found = True
ranu2 = ports.get("ranu")
udpport = True
ran_udp2 = (list(it.zip_longest(*[iter(ranu2[0])] * 2))) # split strings by groups of 2 for port ranges
for ru in compile_rant_port2(ran_udp2):
obj.append(ru)
print("compiled udp only range objects")
if "cm" in ports:
items_found = True
tcpport = True
cm2 = ports.get("cm")
for c in compile_port2(cm2):
obj.append(c)
print("compiled worded objects\n\n")
if not items_found:
print("no items found")
uj5u.com熱心網友回復:
我是否正確理解您在問為什么第一個條款
if ports.get("tcp"):
tcp2 = ports.get("tcp")
tcpport = True
for t in compile_port2(tcp2):
obj.append(t)
print("compiled tcp only objects")
當埠中存在“tcp”時,它是唯一運行的嗎?這就是 if elif else 塊應該如何作業。Elif 代表 else if,即,“如果在我們之前發生的事情不是真的,那么接下來試試這個”
如果你想要多個東西,那么使用多個 if 塊而不是 elif。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364853.html
上一篇:IFS的范圍大小不匹配。預期行數:1。列數:1。實際行數:1000,列數:1
下一篇:新建一行復選框
