Search code examples
pythonsortingip-address

How to sort list of lists using sorting key from inner lists?


I have a table that looks like this:

list_ip=[
  ['192.168.1.15', 10, 20],
  ['192.168.0.20', 15, 15],
  ['10.0.0.5', 50, 5],
  ['10.0.0.2', 55, 5]]

The result should be:

[['10.0.0.2', 55, 5],
 ['10.0.0.5', 50, 5],
 ['192.168.0.20',15,15],
 ['192.168.1.15', 10, 20]]

When I have just list of IP addresses I can sort them using:

import ipaddress 
list_ip=sorted(list_ip, key = ipaddress.IPv4Address)

However I cannot figure out how to do it with extra columns.


Solution

  • import ipaddress 
    list_ip = sorted(list_ip, key = lambda x: ipaddress.IPv4Address(x[0]))