我希望根据元组的第二个值对该字典进行排序
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之前 我该如何解决?
答案 0 :(得分:1)
如果只需要一个已排序的元组列表,则可以使用类似以下的丑陋的东西:
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
是您的字典。