Reputation: 1614
Say I have
apple.berry.cherry.za
100.100.100.100
100.100.100.20
apple.berry.banna.au
and I want
100.100.100.20
100.100.100.100
apple.berry.cherry.au
apple.berry.banna.za
I have the following python code which sorts FQN hostnames the way I want, but it only does alpha-numeric sorting on IP addresses:
#!/bin/python
from fileinput import input
for y in sorted([x.strip().split('.')[::-1] for x in input()]): print '.'.join(y[::-1])
I can add a function to convert a triplet to an integer:
def atoi(text):
return int(text) if text.isdigit() else text
But because I don't know python, I don't know how to call atoi() on each element of the list before it is sorted. How to do?
Upvotes: 1
Views: 127
Reputation: 1213
You can apply a function to each element of the list by using map filter. So it'd be:
for y in sorted([map(atoi, x.strip().split('.')[::-1]) for x in input()]):
print '.'.join(y[::-1])
Edit: As pointed by @Slam, if you decide to use Python 3 one day, translating the foregoing code won't be straightforward. It doesn't allow you to compare ints and strings.
Upvotes: 1
Reputation: 8572
If you expect ipv4 only and this is on-time utility script, you can try dirty hack like
sorted(lst, key=lambda x: [i.zfill(3) if i.isdigit() else i for i in x.split('.')][::-1])
If not, you probably wont end up with one-liner. You need natural sorting for digits, which is not available out of the box
Upvotes: 0