如何基于第二个值对元组列表进行排序,而无需硬编码

2024-05-16 19:27:12 发布

您现在位置: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列表中


Tags: 代码编码列表iftitlecontentbookslists
2条回答

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

首次插入密钥时,可以使用defaultdict自动创建新列表:

from collections import defaultdict

result = defaultdict(list)

for item in list_of_tuples:
    key = item[2]
    result[key].append(item)

现在您可以使用result['notes']result['Lists']

好像你在找filter

这将允许您重用一些类似这样的代码(如果您希望更加灵活但不是必需的话,请插入选择器):

inp = [('first_title', 'first_content','notes'),('second_title','second_content','Lists'), ('third_title', 'third_content','Books'), ('fourth_title', 'fourth_content','Chores')]

def get_by(category, l, selector=lambda x: x[2]):
    return filter(l, lambda x: selector(x) == category)

然后,我可以获得以下类别:

get_by('Books', inp)

或者,我可以根据某些其他条件更改选择器和过滤器:

get_by('first_title', inp, selector=lambda x: x[0])

相关问题 更多 >