我有一段代码看起来像这样:
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 进行排序,但像这样:
192.168.102.105
192.168.204.111
192.168.99.11
这还不够好,因为它无法识别 99 是小于 102 或 204 的数字。我希望输出如下所示:
192.168.99.11
192.168.102.105
192.168.204.111
我找到了 this ,但我不确定如何在我的代码中实现它,或者因为我使用字典,它是否可能实现。我在这里有哪些选择?
最佳答案
您可以使用自定义 key
函数来返回字符串的可排序表示:
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()
函数接受一个 IP 地址字符串,如 '192.168.102.105'
并将其转换为整数元组 (192, 168, 102 , 105)
。 Python 内置支持按字典顺序对元组进行排序。
更新:实际上使用 inet_aton()
可以更轻松地完成此操作socket
模块中的函数:
import socket
items = sorted(ipCount.items(), key=lambda item: socket.inet_aton(item[0]))
关于python - 如何在 Python 中对存储在字典中的 IP 地址进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6545023/