如何uniqufy元组的元素? [英] How to uniqufy the tuple element?

查看:212
本文介绍了如何uniqufy元组的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字典的结果元组。

 的结果=({'名':'XXX','分数':120L},{'名':'XXX','分数':100L},{名称':'YYY,分数:10L})
 

我想uniqify它。 uniqify术后的结果=({'名':'XXX','分数':120L},{'名':'YYY,分数:10L})

结果只包含了在同一个字典每个名称字典最高得分。最终的结果应该是在字典的格式相同,即元组

解决方案

 从运营商进口itemgetter

名称=组(D ['名称']为d。在结果)
uniq的= []
在名称名称:
    成绩= [在结果资源的资源,如果资源['名称'] ==名称]
    uniq.append(MAX(得分,关键= itemgetter('分数')))
 

我敢肯定有一个较短的解决方案,但你将无法避免在某种程度上首先按名称过滤分数,然后找到最大为每名。

与名称作为关键字存储分数在字典中肯定是preferable这里。

i have a result tuple of dictionaries.

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

I want to uniqify it. After uniqify operation result = ({'name': 'xxx', 'score': 120L }, {'name': 'yyy', 'score': 10L})

The result contain only one dictionary of each name and the dict should have maximum score. The final result should be in the same format ie tuple of dictionary.

解决方案

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.

这篇关于如何uniqufy元组的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆