python - 根据顶级域(edu、com、org、in)对列表进行排序

标签 python list sorting

给定一个列表,

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/

相关文章:

Python 如何在数组中创建数组?

python - 展开嵌套的 Python 字典

java - 对字符串数组和 int 数组进行排序

python - 如果基于此算法存在,我如何弹出这封信?

python - 使用 matplotlib.colors.Colormap 将标量值映射到 RGB 时出现奇怪的颜色图

python - 打印所有能被 7 整除并包含 7 从 0 到 100 的数字

xml - 使用由文本和数值组成的数据对 xslt 进行排序

python - 使用 multidict 的排列

Python 对两个列表求幂的性能

arrays - 对 n 元素数组进行排序,使前 k 个元素按升序排列最低(就地算法)