2024-09-25 16:34:05 发布
网友
我正在尝试用python制作排行榜,我有以下建议: points = [("Bob",12),("Steve",7),("Alice",9)] 我试图将其分为以下几点: points = [("Bob",12),("Alice",9),("Steve",7)] 我将如何通过编程实现这一点
points = [("Bob",12),("Steve",7),("Alice",9)]
points = [("Bob",12),("Alice",9),("Steve",7)]
我试过了 sorteddata = sorted(data,key=itemgetter(1)) 无济于事
sorteddata = sorted(data,key=itemgetter(1))
提前谢谢-埃文
您可以这样做:-
pts = list(points) pts.sort(key=lambda x:x[1], reverse=True)
输出:-
[('Bob', 12), ('Alice', 9), ('Steve', 7)]
sortedcontainers包中的SortedDict用作带有排序键的dict对象。(http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html)
sortedcontainers
SortedDict
dict
要按值排序,在sortedcollections中还有ValueSortedDict。(http://www.grantjenks.com/docs/sortedcollections/valuesorteddict.html)
sortedcollections
ValueSortedDict
否则,像这样的纯builtin函数可能会有帮助:
builtin
def sort_dict_by_values(dictionary): return dict(sorted(list(dictionary), key=lambda tup: tup[1], reverse=True))
您可以这样做:-
输出:-
sortedcontainers
包中的SortedDict
用作带有排序键的dict
对象。(http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html)要按值排序,在
sortedcollections
中还有ValueSortedDict
。(http://www.grantjenks.com/docs/sortedcollections/valuesorteddict.html)否则,像这样的纯
builtin
函数可能会有帮助:相关问题 更多 >
编程相关推荐