如何检查列表元素中是否存在值?

时间:2019-08-21 16:34:58

标签: python

我需要检查以如下方式构造的列表中是否存在10.0.0.0/16的值:

if highres == False:
    style = '''QWidget {
                   fontsize: 6pt;
                   icon-size: 15px;
               }

               QWidget::indicator {
                   width: 10px;
                   height: 10px;
               }
            '''
    self.setStyleSheet(stylesheet)

在python中最简单的方法是什么?

下面的代码由于明显的原因而无法工作……什么是正确有效的方式?

[{'Type': 'IPV4', 'Value': '216.137.32.0/19'}, {'Type': 'IPV4', 'Value': '13.54.63.128/26'}]

4 个答案:

答案 0 :(得分:1)

您要将字符串与字典进行比较,请使用包含所有IP地址值的列表推导:

if address in [ip['Value'] for ip in current_ips]:

或者,使用any

if any(ip['Value'] == address for ip in current_ips):

另外,您的打印语句中有语法错误,应该是这样的:

print("I've found " + address + " in current IPs list")

答案 1 :(得分:0)

address = '10.0.0.0/16'
current_ips = [{'Type': 'IPV4', 'Value': '216.137.32.0/19'}, {'Type': 'IPV4', 'Value': '13.54.63.128/26'},{'Type': 'IPV4', 'Value': '10.0.0.0/16'}]

for item in current_ips:
    if item['Value'] == address:
        print("I've found {} in current IPs list {}".format(address,item))

输出:

I've found 10.0.0.0/16 in current IPs list {'Type': 'IPV4', 'Value': '10.0.0.0/16'}

答案 2 :(得分:0)

您可以使用以下设置条件替换current_ips条件:

address = '10.0.0.0/16'
current_ips = [{'Type': 'IPV4', 'Value': '216.137.32.0/19'}, {'Type': 'IPV4', 'Value': '13.54.63.128/26'}]

current_ip_values = set(x['Value'] for x in addresses)

if address in current_ip_values:
    print("I've found " + address  + " in current IPs list")

使用集合而不是列表进行这些检查可以进行恒定的时间查找,因此,如果需要根据大量的当前ip列表检查大量这些ip,这将是一种更有效的方法而不是直接依赖列表。

答案 3 :(得分:0)

result = [ip in L['Value'] for L in l if L['Value'] == ip]
if result:
    print('IP {} was found {} times in list'.format(ip,len(l)))
else:
    print('IP {} was not found in list'.format(ip))