如何对存储在 Python 字典中的 IP 地址进行排序? [英] How to sort IP addresses stored in dictionary in Python?
问题描述
我有一段如下所示的代码:
I have a piece of code that looks like this:
ipCount = defaultdict(int)
for logLine in logLines:
date, serverIp, clientIp = logLine.split(" ")
ipCount[clientIp] += 1
for clientIp, hitCount in sorted(ipCount.items), key=operator.itemgetter(0)):
print(clientIp)
它有点像 IP,但就像这样:
and it kind of sorts IP's, but like this:
192.168.102.105
192.168.204.111
192.168.99.11
这还不够好,因为它不能识别 99 是小于 102 或 204 的数字.我希望输出是这样的:
which is not good enough since it does not recognize that 99 is a smaller number than 102 or 204. I would like the output to be like this:
192.168.99.11
192.168.102.105
192.168.204.111
我找到了这个,但我不知道如何实现它在我的代码中,或者甚至可能因为我使用字典.我在这里有哪些选择?谢谢..
I found this, but I am not sure how to implement it in my code, or if it is even possible since I use dictionary. What are my options here? Thank you..
推荐答案
您可以使用自定义 key
函数返回字符串的可排序表示:
You can use a custom key
function to return a sortable representation of your strings:
def split_ip(ip):
"""Split a IP address given as string into a 4-tuple of integers."""
return tuple(int(part) for part in ip.split('.'))
def my_key(item):
return split_ip(item[0])
items = sorted(ipCount.items(), key=my_key)
split_ip()
函数接受一个像 '192.168.102.105'
这样的 IP 地址字符串,并将它变成一个整数元组 (192, 168, 102, 105)
.Python 内置支持按字典顺序对元组进行排序.
The split_ip()
function takes an IP address string like '192.168.102.105'
and turns it into a tuple of integers (192, 168, 102, 105)
. Python has built-in support to sort tuples lexicographically.
更新:使用 实际上可以更轻松地完成此操作
函数:socket
模块中的 inet_aton()
UPDATE: This can actually be done even easier using the inet_aton()
function in the socket
module:
import socket
items = sorted(ipCount.items(), key=lambda item: socket.inet_aton(item[0]))
这篇关于如何对存储在 Python 字典中的 IP 地址进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!