简体   繁体   English

如何在python中同时执行两个循环?

[英]How to execute two loop simultaneously in python?

I have two lists: 我有两个清单:

 host_list = ["10.3.11.250", "10.3.24.45", "10.5.3.5","10.3.4.5"]
 ip_value = ["34.45.34.5", "10.3.11.250","10.3.4.5"]

I want to check whether the data of host_list is present in ip_value or not if it is then append the ip_value to another list. 我想检查host_list的数据是否存在于ip_value中,如果它随后将ip_value附加到另一个列表中。 I am doing in this way check the following code: 我正在以这种方式检查以下代码:

for host,ip in zip(host_list ,ip_value):
    if host_list == ip_value
        list_ip = list_ip.append(ip)

But it does nothing.Why? 但是什么也没做。为什么? and what should list_ip returns it will returns: {"10.3.11.250", "10.3.4.5"} list_ip应该返回的内容将返回:{“ 10.3.11.250”,“ 10.3.4.5”}

These are sets , not lists. 这些是集合 ,而不是列表。 You can calculate a difference of them: 您可以计算出它们之间的差异:

list_ip = host_list - ip_value

returns 退货

{'10.5.3.5', '10.3.24.45'}

Edited : ok, now they are two lists. 编辑 :好的,现在它们是两个列表。 Change the code to: 将代码更改为:

list_ip = list(set(host_list) - set(ip_value))

returns 退货

['10.5.3.5', '10.3.24.45']

使用set

another_list = list(set(host_list) - set(ip_value))

To answer the question, why does the code you give do nothing: 要回答这个问题,为什么您给出的代码什么都不做:

for host,ip in zip(host_list ,ip_value): 
    if host_list == ip_value 
        list_ip = list_ip.append(ip)

You are comparing host_list to ip_value, and not comparing host to ip. 您正在将host_list与ip_value进行比较,而不是将host与ip进行比较。 host_list != ip_value, thus the next statement is never executed. host_list!= ip_value,因此从不执行下一条语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM