首页 > 解决方案 > 如何根据第二个值对元组列表进行排序而不对其进行硬编码

问题描述

我有一个元组列表。

[('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列表中。

标签: python

解决方案


您想创建一个列表字典,其中每个元组中的第三个值用作键。

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']等。


推荐阅读