基于多个键对元组进行排序并返回最上面的结果

2024-06-07 20:58:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个清单:

[
('abilty', 'ability', 14, 1), 
('aand', 'wand', 14, 1), 
('aand', 'sand', 14, 1), 
('aand', 'land', 272, 1), 
('aand', 'hand', 817, 1), 
('aand', 'and', 38093, 1), 
('aand', 'band', 38093, 1), 
('aand', 'iand', 38093, 1), 
('aand', 'fand', 38093, 1)]

在一个单词的列表中,如果有多个值(例如aand有8个匹配值),那么我想根据第3个属性对它们进行排序,并选择第一个最高的值。例如,在这个示例中,我的结果应该是

[
('abilty', 'ability', 14, 1),  
('aand', 'and', 38093, 1), 
]

我尝试了一些东西,但不幸的是它不起作用。你能帮我吗?谢谢。你知道吗


Tags: and列表band属性排序wand单词hand
2条回答

首先对列表排序:

>>> new_lis = sorted(lis,key=lambda x : (x[0],x[2]),reverse = True) #lis is your list

>>> new_lis
[('abilty', 'ability', 14, 1), ('aand', 'and', 38093, 1), ('aand', 'band', 38093, 1), ('aand', 'iand', 38093, 1), ('aand', 'fand', 38093, 1), ('aand', 'hand', 817, 1), ('aand', 'land', 272, 1), ('aand', 'wand', 14, 1), ('aand', 'sand', 14, 1)]

现在使用itertools.groupby每个组只获取一个项目:

>>> from itertools import groupby
>>> [next(v) for k,v in groupby(new_lis,key=lambda x:x[0])]
[('abilty', 'ability', 14, 1), ('aand', 'and', 38093, 1)]

上述方法的总复杂度为O(NlogN)。你知道吗

您也可以在这里使用collections.defauldict,复杂性O(N)

>>> from collections import defaultdict
>>> dic=defaultdict(list)
>>> for x in lis:
...     dic[x[0]].append(x)
...     
>>> [max(val,key=lambda x: x[2]) for val in dic.values()]
[('aand', 'and', 38093, 1), ('abilty', 'ability', 14, 1)]

在本例中使用itemgetter

>>> student_tuples = [
        ('john', 'A', 15),
        ('jane', 'B', 12),
        ('dave', 'B', 10),
]

>>> from operator import itemgetter, attrgetter

>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

对你来说

l=[
('abilty', 'ability', 14, 1), 
('aand', 'wand', 14, 1), 
('aand', 'sand', 14, 1), 
('aand', 'land', 272, 1), 
('aand', 'hand', 817, 1), 
('aand', 'and', 38093, 1), 
('aand', 'band', 38093, 1), 
('aand', 'iand', 38093, 1), 
('aand', 'fand', 38093, 1)]

from operator import itemgetter, attrgetter

sorted_l = sorted(sorted(l, key=itemgetter(0)), key=itemgetter(2), reverse = True)

s = ''

for x in sorted_l:
    if (x[0] != s):
        s = x[0]
        print x

相关问题 更多 >

    热门问题