在指定具有第一优先级的列表后,我需要选择每个唯一名称具有最小值的列表
原始嵌套列表:
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
,请注意,该函数与 itertools
unique_everseen
recipe 相同.
关于python - 在确定具有第一优先级的列表后,通过选择具有最小值的列表来过滤嵌套列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50946298/