gpt4 book ai didi

python - 将 IP 列表转换为相应 IP 范围的列表 (python)

转载 作者:行者123 更新时间:2023-11-28 21:31:31 26 4
gpt4 key购买 nike

我想将 IP 列表转换为相应 IP 范围的列表。例如:

iplist = ['137.226.161.121', '134.130.4.1', '137.226.161.149', '137.226.161.221', '137.226.161.240', '137.226.161.237', '8.8.8.8', '8.8.4.4', '137.226.161.189', '137.226.161.245', '137.226.161.172', '137.226.161.241', '137.226.161.234', '137.226.161.236', '134.130.5.1']

ipranges = ['137.226.161.0/24', '134.130.4.0/24', '8.8.8.0/24', '8.8.4.0/24', '134.130.5.0/24']

最有效的方法是什么?我还没有找到提供类似功能的模块。使用此功能的原因是,应将一长串 IP(超过 1000 个 ip)转换为子网列表,以提高可读性。

谢谢

最佳答案

如果我理解正确的话,您只想根据前 24 位 (/24) 相同进行匹配。对于这些任务,我推荐 set :

iplist = ['137.226.161.121', '134.130.4.1', '137.226.161.149', '137.226.161.221', '137.226.161.240', '137.226.161.237', '8.8.8.8', '8.8.4.4', '137.226.161.189', '137.226.161.245', '137.226.161.172', '137.226.161.241', '137.226.161.234', '137.226.161.236', '134.130.5.1']

ipset = set()
for i in iplist:
ipset.add(".".join(i.split(".")[:-1]))

ipranges = [p + ".0/24" for p in ipset]
print(ipranges)

这会打印: ['134.130.5.0/24', '8.8.4.0/24', '8.8.8.0/24', '134.130.4.0/24', '137.226.161.0/24']

那么这段代码的作用是什么?

首先,我们遍历列表并截掉每个 IP 的最后一段:

segments = "8.8.8.8".split(".")  # segments == ["8", "8", "8", "8"]
segments_cut = segments[:-1] # segments_cut == ["8", "8", "8"]
prefix = ".".join(segments_cut) # prefix == "8.8.8"

现在我们将这些前缀添加到 set 。一条Python set只允许独特的元素。结果是:ìpset == {'134.130.5', '8.8.4', '8.8.8', '134.130.4', '137.226.161'}

最后,我们迭代该集合并附加后缀“.0/24”来表示子网。

编辑:关于“效率”

我喜欢answer by darkless ,但只需知道我的解决方案明显更快(1.2 秒 vs 0.09 秒):

>>> import timeit
>>> # darkless' ipaddress solution
>>> timeit.timeit("[str(ipaddress.ip_network('{}/24'.format(ip), strict=False)) for ip in iplist]", setup="import ipaddress;iplist = ['137.226.161.121', '134.130.4.1', '137.226.161.149', '137.226.161.221', '137.226.161.240', '137.226.161.237', '8.8.8.8', '8.8.4.4', '137.226.161.189', '137.226.161.245', '137.226.161.172', '137.226.161.241', '137.226.161.234', '137.226.161.236', '134.130.5.1']", number=10000)
1.186...
>>> # My solution
>>> timeit.timeit("[p + '.0/24' for p in {'.'.join(i.split('.')[:-1]) for i in iplist}]", setup="import ipaddress;iplist = ['137.226.161.121', '134.130.4.1', '137.226.161.149', '137.226.161.221', '137.226.161.240', '137.226.161.237', '8.8.8.8', '8.8.4.4', '137.226.161.189', '137.226.161.245', '137.226.161.172', '137.226.161.241', '137.226.161.234', '137.226.161.236', '134.130.5.1']", number=10000)
0.096...

关于python - 将 IP 列表转换为相应 IP 范围的列表 (python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58028027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com