Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort the list based on the top level domain (edu, com, org, in)

Given a list,

url = ["www.annauniv.edu", "www.google.com", "www.ndtv.com", "www.website.org", "www.bis.org.in", "www.rbi.org.in"];

Sort the list based on the top level domain (edu, com, org, in) I am very new to python, i tried to solve this by sorting the list by the second last term i.e "d,o,r,i". But the output I get is not as expected could you help me understand why?


url = ["www.annauniv.edu", "www.google.com", "www.ndtv.com", "www.website.org", "www.bis.org.in", "www.rbi.org.in"]
def myFn(s):
    return s[-2]

print sorted(url,key=myFn) `

i get the following output:

['www.annauniv.edu', 'www.bis.org.in', 'www.rbi.org.in', 'www.google.com', 'www.ndtv.com', 'www.website.org']

But when i try with this list url=["x.ax","u.ax","x.cx","y.cx","y.by"] i get the corect result i.e

['x.ax', 'u.ax', 'y.by', 'x.cx', 'y.cx']
like image 895
Ashish Kumar S Avatar asked Dec 24 '22 00:12

Ashish Kumar S


2 Answers

More generally, you probably also want "www.google.com" to come before "www.ndtv.com", and "web3.example.com" to come before "www.example.com", right? Here's how you can do that:

urls = ["www.annauniv.edu", "www.google.com", "www.ndtv.com", "www.website.org", "www.bis.org.in", "www.rbi.org.in"]

def key_function(s):
    # Turn "www.google.com" into ["www", "google", "com"], then
    # reverse it to ["com", "google", "www"].
    return list(reversed(s.split('.')))

# Now this will sort ".com" before ".edu", "google.com" before "ndtv.com",
# and so on.
print(sorted(urls, key=key_function))
like image 180
Kirk Strauser Avatar answered Dec 25 '22 12:12

Kirk Strauser


Because you're doing -2, so it gets the second-to-last characters, so some stuff ending like com would be just om, so use:

print(sorted(url,key=lambda x: x.split('.')[-1]))

Jab's version is this using a function, Kirk's one is using reversed, but still, his could use [::-1] instead.

Edit: (thanks to taurus05 for correcting me)

def func(x):
    d = {'edu':'e','com':'m','org':'o'}
    return d.get(x.split('.')[-1],'z')

print(sorted(urls, key=func))
like image 41
U12-Forward Avatar answered Dec 25 '22 14:12

U12-Forward