列表中的 Python 用户输入

我是 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


猛跑小猪
浏览 175回答 1
1回答

隔江千里

为什么需要循环?使用in检查,如果在列表中存在的输入值,并相应如下:option=input("option: ")iplist=['192.168.1.1', '192.168.1.2', '192.168.1.254']if option in iplist:&nbsp; &nbsp;# do the rest&nbsp; &nbsp; pass或:如果要获取Index列表中元素的 :for index, elem in enumerate(iplist):&nbsp; &nbsp; if option == elem:&nbsp; &nbsp; &nbsp; &nbsp; print("Element found at Index: {}".format(index))输出:option: 192.168.1.2Element found at Index: 1编辑 2:首先要注意以下几点:从用户那里获取输入并将其转换为 anint因为您无法使用 str 索引访问列表:我仍然没有看到循环点所以:import subprocessoption= int(input("option: "))&nbsp; &nbsp; # 1iplist=['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:&nbsp; &nbsp; Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python