def last_name(str):
return str.split()[1]
names = ["Isaac Newton", "Fred Newton", "Niels Bohr"]
print("s:", sorted(names, key=last_name))
print("s:", sorted(names, key=last_name, reverse=True))输出:
s: ['Niels Bohr', 'Isaac Newton', 'Fred Newton']
s: ['Isaac Newton', 'Fred Newton', 'Niels Bohr']当我使用reverse=True时,是不是应该是这样的:['Fred Newton','Isaac Newton', 'Niels Bohr']
发布于 2016-11-06 16:14:23
Python的排序算法是稳定的。如果两个值具有相同的key(value)结果,那么它们的相对顺序是相同的。反转只适用于不同的key(value)结果。
因为key('Isaac Newton')和key('Fred Newton')都生成'Newton',所以这两个字符串按它们原来的相对顺序保留。reverse=True标志仅在'Bohr'在'Newton'之前或之后排序时才会影响。
如果需要颠倒它们的相对顺序,请向前排序,然后反转结果列表。
https://stackoverflow.com/questions/40451467
复制相似问题