我正在尝试获取包含“IP 地址”和子网掩码 (1.0.0.0/24) 的列表,并计算该列表中“IP 地址”的总数。但是,我试图避免计算相同的 IP 地址'但具有更高的子网掩码。
示例 1.0.0.0/24 1.0.0.0/16 1.0.0.0/8
这里我只想使用/8来计算IP地址,因为它包含/16和/24
我已将所有 IP 地址放入一个列表 newSet 中,就像这样...
示例 1.0.0.0/24 1.0.0.0/16 1.0.0.0/8 2.0.0.0/24 2.0.0.0/16 等等....
然后我使用以下代码弹出子网掩码/24、/16、/8 等...就像这样
subIP = [i.split('/', 1)[1] for i in newSet]
然后我通过全局声明的ipTotal计算IP空间
for element in subIP:
y = 32 - int(element)
x = pow(2, y)
ipTotal = ipTotal + x
但是,我现在正在计算 1.0.0.0/24 、 1.0.0.0/16 和 1.0.0.0/8 ,而我所需要做的就是计算 1.0.0.0/8 。
基本上,我过度计算了 IP 空间量。
我需要如何解决这个问题?我考虑过将 1.0.0.0 放入一个列表中,然后将/24 放入另一个列表中...然后运行嵌套的 for 循环进行比较,但我很确定这行不通。
最佳答案
ip_dict = {}
for ip_subnet in newSet:
ip,subnet = ip_subnet.split('/')
subnet = int(subnet)
if ip not in ip_dict or ip_dict[ip] > subnet:
ip_dict[ip] = subnet
updated_list = [str(ip)+"/"+str(subnet) for ip,subnet in ip_dict.iteritems()]
ipTotal = 0
for subnet in ip_dict.values():
y = 32 - int(subnet)
x = pow(2, y)
ipTotal = ipTotal + x
您使用一个非常适合唯一键,值
配对的字典,只需执行您想要的检查,然后将地址重新组成列表即可。
updated_list
将是具有该 IP 的最小子网的唯一 IP 地址的列表。
ip_dict.values()
给出这些唯一 IP 的子网列表。
关于python - 比较列表并提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25070202/