How to uniqufy the tuple element?

前端 未结 4 1728
星月不相逢
星月不相逢 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:24

    from operator import itemgetter
    
    names = set(d['name'] for d in result)
    uniq = []
    for name in names:
        scores = [res for res in result if res['name'] == name]
        uniq.append(max(scores, key=itemgetter('score')))
    

    I'm sure there is a shorter solution, but you won't be able to avoid filtering the scores by name in some way first, then find the maximum for each name.

    Storing scores in a dictionary with names as keys would definitely be preferable here.

提交回复
热议问题