首页 > 解决方案 > 如何对包含元组的字典进行排序

问题描述

我希望根据元组的第二个值对这个字典进行排序

print(normalizedTermFrequency)

c=sorted(normalizedTermFrequency.items(),key=lambda t:t[1][1],reverse=True)

print(c)

输出:

{0: [('the', 0.2857142857142857), ('universe', 0.14285714285714285), ('has', 0.14285714285714285), ('very', 0.14285714285714285), ('many', 0.14285714285714285), ('stars', 0.14285714285714285)], 1: [('the', 0.2), ('galaxy', 0.2), ('contains', 0.2), ('many', 0.2), ('stars', 0.2)], 2: [('the', 0.1), ('cold', 0.2), ('breeze', 0.1), ('of', 0.1), ('winter', 0.1), ('made', 0.1), ('it', 0.1), ('very', 0.1), ('outside', 0.1)]}

[(0, [('the', 0.2857142857142857), ('universe', 0.14285714285714285), ('has', 0.14285714285714285), ('very', 0.14285714285714285), ('many', 0.14285714285714285), ('stars', 0.14285714285714285)]), (1, [('the', 0.2), ('galaxy', 0.2), ('contains', 0.2), ('many', 0.2), ('stars', 0.2)]), (2, [('the', 0.1), ('cold', 0.2), ('breeze', 0.1), ('of', 0.1), ('winter', 0.1), ('made', 0.1), ('it', 0.1), ('very', 0.1), ('outside', 0.1)])]

但是正如我们在第二个输出中看到的那样,第二个键 0.1 出现在 0.2 之前我该如何解决这个问题?

标签: python-3.xsortingdictionarytuples

解决方案


如果你只想要一个排序的元组列表,你可以使用一些丑陋的东西,比如:

sorted([y for x in dic.values() for y in x], key=lambda x: x[1], reverse=True)

如果要对值进行排序但保留映射,则应该这样做:

for key, value in dic.items():
    dic[key] = sorted(dic[key], key=lambda x: x[1], reverse=True)

dic你的字典在哪里。


推荐阅读