How to uniqufy the tuple element?

前端 未结 4 1729
星月不相逢
星月不相逢 2021-01-19 06:48

i have a result tuple of dictionaries.

result = ({\'name\': \'xxx\', \'score\': 120L }, {\'name\': \'xxx\', \'score\': 100L}, {\'name\': \'yyy\', \'score\':          


        
4条回答
  •  盖世英雄少女心
    2021-01-19 07:09

    I would reconsider the data structure to fit your needs better (for example dict hashed with name with list of scores as value), but I would do like this:

    import operator as op
    import itertools as it
    
    result = ({'name': 'xxx', 'score': 120L },
              {'name': 'xxx', 'score': 100L},
              {'name': 'xxx', 'score': 10L},
              {'name':'yyy', 'score':20})
    # groupby
    
    highscores = tuple(max(namegroup, key=op.itemgetter('score'))
                       for name,namegroup in it.groupby(result,
                                                        key=op.itemgetter('name'))
                       )
    print highscores
    

提交回复
热议问题