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']
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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With