如何在python中对python二维数组排序

2024-09-25 16:34:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python制作排行榜,我有以下建议: points = [("Bob",12),("Steve",7),("Alice",9)] 我试图将其分为以下几点: points = [("Bob",12),("Alice",9),("Steve",7)] 我将如何通过编程实现这一点

我试过了 sorteddata = sorted(data,key=itemgetter(1)) 无济于事

提前谢谢-埃文


Tags: keydata编程建议pointsstevebobsorted
2条回答

您可以这样做:-

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

要按值排序,在sortedcollections中还有ValueSortedDict。(http://www.grantjenks.com/docs/sortedcollections/valuesorteddict.html

否则,像这样的纯builtin函数可能会有帮助:

def sort_dict_by_values(dictionary):
    return dict(sorted(list(dictionary), key=lambda tup: tup[1], reverse=True))

相关问题 更多 >