嗨,我是python编程的新手,在任何地方都找不到此帮助
我有一个要在指定列表exp中搜索的用户输入值:
option=input("option: ")
iplist=['192.168.1.1', '192.168.1.2', '192.168.1.254']
while option <= "3":
#this is wrong. Help!
nub = iplist[option]
subprocess.call(["ping", nub])
我希望用户的选项成为该程序列表中的数字,输出应为:
Option : 0
Pinging 192.168.1.1 with 32 bytes of data:
Reply from 192.168.1.1: bytes=32 time=2ms TTL=64
Reply from 192.168.1.1: bytes=32 time=2ms TTL=64
Reply from 192.168.1.1: bytes=32 time=2ms TTL=64
Reply from 192.168.1.1: bytes=32 time=2ms TTL=64
Ping statistics for 192.168.1.1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 2ms, Maximum = 2ms, Average = 2ms
答案 0 :(得分:0)
为什么需要循环?使用in
检查输入值是否存在于列表中,并按照以下步骤进行操作:
option=input("option: ")
iplist=['192.168.1.1', '192.168.1.2', '192.168.1.254']
if option in iplist:
# do the rest
pass
OR :
如果要获取列表中元素的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 :
首先要注意几件事:
从用户那里获取输入并将其转换为int
,因为您无法使用str索引访问列表:
我仍然看不到循环点
所以:
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),