给定一个列表,
url = ["www.annauniv.edu", "www.google.com", "www.ndtv.com", "www.website.org", "www.bis.org.in", "www.rbi.org.in"]
;
根据顶级域(edu、com、org、in)对列表进行排序 我是 python 的新手,我试图通过按倒数第二个术语(即“d、o、r、i”)对列表进行排序来解决这个问题。但是我得到的输出不是预期的,你能帮我理解为什么吗?
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) `
我得到以下输出:
['www.annauniv.edu', 'www.bis.org.in', 'www.rbi.org.in', 'www.google.com', 'www.ndtv.com', 'www.website.org']
但是当我尝试使用这个列表时 url=["x.ax","u.ax","x.cx","y.cx","y.by"]
我得到了正确的结果,即
['x.ax', 'u.ax', 'y.by', 'x.cx', 'y.cx']
最佳答案
更一般地说,您可能还希望“www.google.com”出现在“www.ndtv.com”之前,而“web3.example.com”出现在“www.example.com”之前,对吗?以下是您可以如何做到这一点:
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))
关于python - 根据顶级域(edu、com、org、in)对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54937967/