How to sort IP addresses stored in dictionary in Python?

后端 未结 8 1680
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 08:32

I have a piece of code that looks like this:

ipCount = defaultdict(int)

for logLine in logLines:
    date, serverIp, clientIp = logLine.split(\" \")
    ipC         


        
8条回答
  •  無奈伤痛
    2020-11-29 08:51

    Use the key parameter of sorted to convert your ip to an integer, for example:

    list_of_ips = ['192.168.204.111', '192.168.99.11', '192.168.102.105']
    sorted(list_of_ips, key=lambda ip: long(''.join(["%02X" % long(i) for i in ip.split('.')]), 16))
    

    EDIT:

    Gryphius proposes a solution with the socket module, and so why not use it to make the conversion from ip to long as it is cleaner:

    from socket import inet_aton
    import struct
    list_of_ips = ['192.168.204.111', '192.168.99.11', '192.168.102.105']
    sorted(list_of_ips, key=lambda ip: struct.unpack("!L", inet_aton(ip))[0])
    

提交回复
热议问题