python - Sorting list of tuples based on multiple keys and returning top results -
i have list that:
[ ('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)]
in list 1 word if there more 1 value (for example there 8 match aand )then want sort them according 3rd attribute , choose first highest one. example in sample result should
[ ('abilty', 'ability', 14, 1), ('aand', 'and', 38093, 1), ]
i try unfortunately not work. me ? thanks.
first sort list:
>>> new_lis = sorted(lis,key=lambda x : (x[0],x[2]),reverse = true) #lis 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)]
now 1 item per group use itertools.groupby
:
>>> itertools import groupby >>> [next(v) k,v in groupby(new_lis,key=lambda x:x[0])] [('abilty', 'ability', 14, 1), ('aand', 'and', 38093, 1)]
total complexity of above method o(nlogn)
.
you can use collections.defauldict
here, complexity o(n)
:
>>> collections import defaultdict >>> dic=defaultdict(list) >>> x in lis: ... dic[x[0]].append(x) ... >>> [max(val,key=lambda x: x[2]) val in dic.values()] [('aand', 'and', 38093, 1), ('abilty', 'ability', 14, 1)]
Comments
Post a Comment