如何对具有IP子网的列表列表进行排序python

Mat*_*ely 5 python networking list cidr

我是一个十足的菜鸟,让 google 制作了我的第一个 python 脚本。

我正在打开 2 个文件并从列表 2 中删除列表 1。

修改 list2 以删除列表 1 中的内容后,我想按 IP 网络对列表进行排序。例如:

1.1.1.1/24
1.1.1.1/32
5.5.5.5/20
10.10.11.12/26
10.11.10.4/32
Run Code Online (Sandbox Code Playgroud)

目前正在排序

1.1.1.1/24
1.1.1.1/32
10.10.11.12/26
10.11.10.4/32
5.5.5.5/20
Run Code Online (Sandbox Code Playgroud)

代码:

import os
import sys
import random
import re

text_file = open("D:/file/update2.txt", "rt")
lines = str(text_file.readlines())
text_file.close()
ip_address = r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d] 
{1,3}/\d{1,2})'
foundip = re.findall( ip_address, lines )


text_file2 = open("D:/file/Block.txt", "rt")
lines2 = str(text_file2.readlines())
text_file2.close()
foundip2 = re.findall( ip_address, lines2 )


test =(list(set(foundip2) - set(foundip)))

items = sorted(test)
print (*items, sep = "\n")
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Jea*_*bre 4

默认排序是字母数字排序。您需要从 IP 地址生成整数元组以用作排序键函数。我使用re.findall“数字”表达式,然后转换为 int (但还有其他解决方案,split例如)

import re

ip_list = """1.1.1.1/24
1.1.1.1/32
10.10.11.12/26
10.11.10.4/32
5.5.5.5/20""".splitlines()

print(sorted(ip_list,key=lambda x : [int(m) for m in re.findall("\d+",x)]))
Run Code Online (Sandbox Code Playgroud)

印刷:

['1.1.1.1/24', '1.1.1.1/32', '5.5.5.5/20', '10.10.11.12/26', '10.11.10.4/32']
Run Code Online (Sandbox Code Playgroud)