python - 如何根据第二个值对元组列表进行排序而不对其进行硬编码
问题描述
我有一个元组列表。
[('first_title', 'first_content','notes'),('second_title','second_content','Lists'), ('third_title', 'third_content','Books'), ('fourth_title', 'fourth_content','Chores')
我想在代码中获取每个元组并将它们放在一个列表中,其中该列表仅包含具有相同第二个值(从 0 开始)但没有硬编码第二个值或列表长度的元组。所以结果看起来像......
notes = [('first_title, 'first_content, 'notes')]
Lists = [('second_title, 'second_content, 'Lists')]
Books = [('third_title, 'third_content, 'Books')]
Chores = [('fourth_title, 'fourth_content, 'Chores')]
所以我真的做不到...
if x[2] == 'Lists'
因为它是硬编码的。
例如,如果有另一个元组的第二个元素(从 0 开始)等于,'Books'
那么它将在Books
列表中。
解决方案
您想创建一个列表字典,其中每个元组中的第三个值用作键。
defaultdict
首次插入密钥时,您可以使用 a自动创建新列表:
from collections import defaultdict
result = defaultdict(list)
for item in list_of_tuples:
key = item[2]
result[key].append(item)
现在您可以使用result['notes']
,result['Lists']
等。
推荐阅读
- google-bigquery - 在 BigQuery 上交叉应用的替代方法
- python - 是否可以创建一个条形图,其中 Y 是 Pandas 数据框中列的不同值的计数?
- javascript - 怎么获得从目录上传中获取单个文件?
- tcl - TCL命令让我可以得到上个月?
- javascript - 如何使用 jQuery-tagEditor 不允许用户手动编辑添加新标签?
- angular - 为什么 runOutsideAngular 和 detectChanges 的组合只重新初始化组件一次?
- javascript - 未捕获的错误:Bootstrap 的 JavaScript 需要 Vue 2.4 组件中的 jQuery
- javascript - Grails:将自定义 javaScript 添加到 f:all 中呈现的字段
- azure-ad-b2c - B2C如何支持匿名用户?
- java - 如何使属性测试获得实体生成器可以返回的实体集合?