python-3.x - 如何对包含元组的字典进行排序
问题描述
我希望根据元组的第二个值对这个字典进行排序
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 之前我该如何解决这个问题?
解决方案
如果你只想要一个排序的元组列表,你可以使用一些丑陋的东西,比如:
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
你的字典在哪里。
推荐阅读
- kubernetes - Kubernetes CRD 中状态的最大大小?
- python - Tkinter GUI root.after()
- html - 即使在打字时如何显示我的标题背景颜色
- javascript - 如何解决这个“for循环”练习
- sql - 比较 pl/sql 中的日期
- java - 使用 ConfigProperties 注入对象的 Junit 测试为空
- r - r 中有没有办法使用对象名称的字符列表来改变这些对象与 base::lapply 和 dplyr::mutate
- indexing - 使用数组进行数组索引
- scheme - 如果没有对 Scheme 的下限和舍入函数的先验知识,如何完成 SICP 练习 1.45(制作第 n 个根函数)?
- python - IndexError:使用 For 循环时 Python 3 中的列表索引超出范围