代码之家  ›  专栏  ›  技术社区  ›  Ahmad Senousi

通过在确定具有第一优先级的列表后选择具有最小值的列表来筛选嵌套列表?

  •  2
  • Ahmad Senousi  · 技术社区  · 6 年前

    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']]] 
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   jpp    6 年前

    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]]]
    

    toolz itertools unique_everseen recipe