How to uniqufy the tuple element?

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

    I would create an intermediate dictionary mapping each name to the maximum score for that name, then turn it back to a tuple of dicts afterwards:

    >>> result = ({'name': 'xxx', 'score': 120L }, {'name': 'xxx', 'score': 100L}, {'name': 'xxx', 'score': 10L}, {'name':'yyy', 'score':20})
    >>> from collections import defaultdict
    >>> max_scores = defaultdict(int)
    >>> for d in result: 
    ...     max_scores[d['name']] = max(d['score'], max_scores[d['name']])
    ... 
    >>> max_scores 
    defaultdict(, {'xxx': 120L, 'yyy': 20})
    >>> tuple({name: score} for (name, score) in max_scores.iteritems()) 
    ({'xxx': 120L}, {'yyy': 20})
    

    Notes: 1) I have added {'name': 'yyy', 'score': 20} to your example data to show it working with a tuple with more than one name.

    2)I use a defaultdict that assumes the minimum value for score is zero. If the score can be negative you will need to change the int parameter of defaultdict(int) to a function that returns a number smaller than the minimum possible score.

    Incidentally I suspect that having a tuple of dictionaries is not the best data structure for what you want to do. Have you considered alternatives, such as having a single dict, perhaps with a list of scores for each name?

提交回复
热议问题