How to sort IP addresses stored in dictionary in Python?

后端 未结 8 1723
隐瞒了意图╮
隐瞒了意图╮ 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:52

    What are my options here?

    The two obvious one that come to my mind are:

    1. Preformatting the strings with the IP when you store them as from the link you put in your question.
    2. Pass a sorting function to sorted() function when you perform the ordering.

    Which is best depends from the amount of data you have to process (you will notice an increased performance for method #1 only for very large amount of data) and from what you will need to do with said sorted list of IP (if you preformat the strings, you might then need to change them again before feeding them as arguments to other functions, for example).

    Example of preformatting

    Maintain the IP as a string, but uses spaces or zeroes to solve the variable number of digits problem:

    >>> ip = '192.168.1.1'
    >>> print('%3s.%3s.%3s.%3s' % tuple(ip.split('.')))
    192.168.  1.  1
    >>> print('%s.%s.%s.%s' % tuple([s.zfill(3) for s in ip.split('.')]))
    192.168.001.001
    

    Example of sorting function

    Well... Ferdinand Beyer in his answer seems to have already offered an excellent solution for this approach! :)

提交回复
热议问题