1 回答

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超10個(gè)贊
為什么需要循環(huán)?使用in檢查,如果在列表中存在的輸入值,并相應(yīng)如下:
option=input("option: ")
iplist=['192.168.1.1', '192.168.1.2', '192.168.1.254']
if option in iplist:
# do the rest
pass
或:
如果要獲取Index列表中元素的 :
for index, elem in enumerate(iplist):
if option == elem:
print("Element found at Index: {}".format(index))
輸出:
option: 192.168.1.2
Element found at Index: 1
編輯 2:
首先要注意以下幾點(diǎn):
從用戶那里獲取輸入并將其轉(zhuǎn)換為 anint因?yàn)槟鸁o法使用 str 索引訪問列表:
我仍然沒有看到循環(huán)點(diǎn)
所以:
import subprocess
option= int(input("option: ")) # 1
iplist=['192.168.1.1', '192.168.1.2', '192.168.1.254']
nub = iplist[option]
subprocess.call(["ping", nub])
輸出:
Pinging 192.168.1.2 with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Ping statistics for 192.168.1.2:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
添加回答
舉報(bào)