在确定具有第一优先级的列表后,按 select 具有最小值的列表过滤嵌套列表?

Filtering a nested list by select a list that have minimum value after determine the lists that have first priority?

我需要 select 在指定具有第一优先级的列表后,每个唯一名称具有最小值的列表,例如

原始嵌套列表:

lst=[[['ahmad','a',5],['ahmad','a',6],['ahmad','c',4],['Emme','b',5],['Emme','b',4]],[['ahmad','b',5],['ahmad','b',6],['ahmad','c',6],['ahmad','c',5],['Meno','c',4],['Emme','b',5],['Moo','b',4],['Moo','a',7],['Moo','a',5]]]

每个列表表示为:['name', 'priority term', value].

优先级为'a',然后是'b',然后是'c'。

想要的结果:

new_lst=[[['ahmad','a',5],['Emme','b',4]],[['ahmad','b',5],['Meno','c',4],['Emme','b',5],['Moo','a',5]]]

更新:

如榜单:

lst=[[['ahmad','red',5,20,'a'],['ahmad','red',6,21,'a'],['ahmad','blue',4,15,'c'],['Emme','red',5,30,'b'],['Emme','red',4,12,'b']],[['ahmad','blue',5,10,'b'],['ahmad','blue',6,13,'b'],['ahmad','blue',6,15,'c'],['ahmad','blue',5,30,'c'],['Meno','green',4,40,'c'],['Emme','green',5,35,'b'],['Moo','red',4,7,'b'],['Moo','red',7,3,'a'],['Moo','red',5,18,'a']]] 

每个列表表示为:['name','color',value, trivial number, 'priority term'].

想要的结果:

new_list=[[['ahmad','red',5,20,'a'],['ahmad','blue',4,15,'c'],['Emme','red',4,12,'b']],[['ahmad','blue',5,10,'b'],['Meno','green',4,40,'c'],['Emme','green',5,35,'b'],['Moo','red',5,18,'a']]] 

您可以使用字典来保存您的优先顺序。然后使用 sorted 后跟 toolz.unique 排序并删除重复名称:

from toolz import unique

priority = {v: k for k, v in enumerate('abc')}

def prioritiser(x):
    return priority[x[1]], x[2]

res = [list(unique(sorted(sublist, key=prioritiser), key=lambda x: x[0])) \
       for sublist in lst]

print(res)

[[['ahmad', 'a', 5], ['Emme', 'b', 4]],
 [['Moo', 'a', 5], ['ahmad', 'b', 5], ['Emme', 'b', 5], ['Meno', 'c', 4]]]

如果您无法访问第 3 方 toolz, note that the function is identical to the itertools unique_everseen recipe