如何在python中对元组列表进行排序[重复]

问题描述 投票:0回答:1

我有一个包含几个像这样的元组的列表:

(label, count)

而且我想按他们的数量对它们进行排序,但是我不知道我该怎么做。我知道python具有内置函数sort(),但我认为我无法在我的情况下使用它。我希望有人知道该怎么做。

示例:

input: [("label 1", 5), ("label 2", 1), ("label 3", 3), ("label 4", 6)]
output: [("label 4", 6), ("label 1", 5), ("label 3", 3), ("label 2", 1)]
python arrays list sorting
1个回答
0
投票
a = [("label 1", 5), ("label 2", 1), ("label 3", 3), ("label 4", 6)]
a = sorted(a, key = lambda x: int(x[1]), reverse = True)

一个变成

[('label 4', 6), ('label 1', 5), ('label 3', 3), ('label 2', 1)]
© www.soinside.com 2019 - 2024. All rights reserved.