How to sort a given IP addresses in ascending order with Python

1 Answer

0 votes
from socket import inet_aton
import struct

lst = ['218.189.1.226', 
       '218.132.0.157',        
       '218.206.1.194', 
       '218.206.0.206']

lst = sorted(lst, key=lambda ip: struct.unpack("!L", inet_aton(ip))[0])

print(*lst, sep='\n')


  
'''
run:
  
218.132.0.157
218.189.0.226
218.206.0.206
218.206.1.194
         
'''

 



answered May 16, 2020 by avibootz

Related questions

1 answer 234 views
2 answers 177 views
1 answer 187 views
1 answer 201 views
2 answers 211 views
1 answer 140 views
1 answer 224 views
...