从列表中选择项目

时间:2017-07-31 15:01:07

标签: python python-3.x

我试图验证计算机是否在工作的特定VLAN上。下面是我得到的代码,但是当我在列表中运行时,我不仅得到了Yes,表示计算机在vlan上,但是你必须连接到vpn以及其他项目。有没有办法让它设置在满足第一个条件时跳过第二个条件或评估第一个条件,如果不满足,则转到第二个条件。我在Windows 7上使用python 3.6.2。

import socket

IP1 = socket.gethostbyname(socket.gethostname())

IpAddress = IP1.split('.')

Work = ['30', '40', '50', '70', '221'];

print (Work)

for ip in Work:
    if IpAddress[2] == ip:
        print ('yes')
        break
    elif IpAddress[2] != ip:
        print ('You must connect to the vpn!!')


print (IP1)

2 个答案:

答案 0 :(得分:0)

看起来您的“else”(在这种情况下为elif)是for循环中条件语句的一部分,因此将针对每次迭代对其进行评估。

Python也有一个for - else构造,它在循环迭代“耗尽”(StopIteration)后输入。这是文件(Python docs

为循环尝试以下代码:

for ip in Work:
    if IpAddress[2] == ip:
        print ('yes')
        break
else:
    print ('You must connect to the vpn!!')

答案 1 :(得分:0)

根本不需要循环来将IP与列表中的IP进行比较。只需使用in

if IpAddress[2] in Work:
    print ('yes')
else:
    print ('You must connect to the vpn!!')

其他一些变体,以防您不仅想要与==进行比较,而是更复杂的事情,例如查看它是否与某些子网掩码相匹配

# also works with more compelx comparisons
if any(IpAddress[2] == ip for ip in Work):
    print ('yes')
else:
    print ('You must connect to the vpn!!')

# if you also want to have the matching element
ip = next((ip for ip in Work if IpAddress[2] == ip), None)
if ip is not None:
    print ('yes, the ip is', ip)
else:
    print ('You must connect to the vpn!!'