本文介绍了如何用端口号对IP地址排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建自己的报告工具,并且试图弄清楚如何用端口号对IP地址进行排序.
I am creating my own reporting tool, and I am trying to figure out how to sort IP address with port number.
如何对带有端口号的IP地址进行排序,这样我首先对IP地址进行排序,然后再对端口号进行排序.我可以对IP地址进行排序,但是当与端口号结合使用时,会变得很困难.
How do I sort an IP address with port number such that I sort the IP address first and then through port number. I am able to sort IP address just fine, but when combining with port numbers, it becomes difficult.
a = ['192.168.0.3 (443/tcp)|', '192.168.0.176 (443/tcp)|', '192.168.0.40 (443/tcp)|', '192.168.0.15 (8443/tcp)|', '192.168.0.16 (8443/tcp)|', '192.168.0.12 (443/tcp)|', '192.168.0.9 (3389/tcp)|', '192.168.0.15 (443/tcp)|', '192.168.0.16 (443/tcp)|', '192.168.0.3 (3389/tcp)|', '192.168.0.14 (443/tcp)|'] print(a.sort(key=lambda s: map(int, s.split('.')))) #this works fine with just IP address not with the current format of (xxx/tcp). The pipe is for delimiters so please ignore.我想先按IP地址对输出进行排序,然后再对每个IP通过端口号进行排序.因此,例如,前几个结果将是:
I would like to get the output sorted by IP address first, and then for each IP to sort via port number. So for example, the first few results would be:
a= ['192.168.0.3 (443/tcp)|', '192.168.0.3 (3389/tcp)|', 192.168.0.9 (3389/tcp)|, ...']推荐答案
使用re.findall:
import re def get_ip_port(x): *ips, port = map(int, re.findall('\d+', x)) return ips, port sorted(a, key=get_ip_port)输出:
['192.168.0.3 (443/tcp)|', '192.168.0.3 (3389/tcp)|', '192.168.0.9 (3389/tcp)|', '192.168.0.12 (443/tcp)|', '192.168.0.14 (443/tcp)|', '192.168.0.15 (443/tcp)|', '192.168.0.15 (8443/tcp)|', '192.168.0.16 (443/tcp)|', '192.168.0.16 (8443/tcp)|', '192.168.0.40 (443/tcp)|', '192.168.0.176 (443/tcp)|']说明:
- map(int, re.findall('\d+', x)):查找所有数字并将其设置为int
- *ips, port:解压上述int的包装,然后重新包装成除最后一个(*ips)和最后一个(port)之外的所有
- sorted(a, key=get_ip_port):由于get_ip_port返回两个键(ips,port),sorted根据需要先对a进行排序,然后按ips和port排序.
- map(int, re.findall('\d+', x)): finds all digits and make them int
- *ips, port: unpacks the above ints and repack into all but last one (*ips) and last one (port)
- sorted(a, key=get_ip_port): as get_ip_port returns two keys (ips,port), sorted sorts the a first by ips and then port, just as desired.
更多推荐
如何用端口号对IP地址排序?
发布评论