Reputation: 16115
I have a list of IPv4 and IPv6 networks created with ipaddress.ip_network()
, which I want to sort (by family first, then value). What would be the best way to do this? Apparently, a naive sort doesn't work:
>>> from ipaddress import ip_network
>>> L = [ip_network(x) for x in ['ff00::/8', 'fd00::/8', '172.16.0.0/12', '10.0.0.0/8']]
>>> L.sort()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/ipaddress.py", line 652, in __lt__
self, other))
TypeError: 10.0.0.0/8 and fd00::/8 are not of the same version
Upvotes: 3
Views: 602
Reputation: 149963
Just use a key
function that would allow to compare the values by type first, something like:
>>> from ipaddress import ip_network, IPv6Network
>>> L = [ip_network(x) for x in ['ff00::/8', 'fd00::/8', '172.16.0.0/12', '10.0.0.0/8']]
>>> L.sort(key=lambda x: (isinstance(x, IPv6Network), x))
>>> L
[IPv4Network('10.0.0.0/8'), IPv4Network('172.16.0.0/12'), IPv6Network('fd00::/8'), IPv6Network('ff00::/8')]
Upvotes: 4