在python中按键减少 [英] Reduce by key in python

查看:42
本文介绍了在python中按键减少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑在 python 中执行此操作的最有效方法.

I'm trying to think through the most efficient way to do this in python.

假设我有一个元组列表:

Suppose I have a list of tuples:

[('dog',12,2), ('cat',15,1), ('dog',11,1), ('cat',15,2), ('dog',10,3), ('cat',16,3)]

假设我有一个函数,它接受其中两个元组并将它们组合起来:

And suppose I have a function which takes two of these tuples and combines them:

def my_reduce(obj1, obj2):
    return (obj1[0],max(obj1[1],obj2[1]),min(obj1[2],obj2[2]))

如何通过键"执行有效的归约,其中此处的键可能是第一个值,因此最终结果将类似于:

How do I perform an efficient reduce by 'key' where the key here could be the first value, so the final result would be something like:

[('dog',12,1), ('cat',16,1)]

推荐答案

如果你想使用你的 my_reducereduce,你可以这样做.实际上很短:

If you want to use your my_reduce and reduce, you can do it this way. It's fairly short, actually:

准备:

from itertools import groupby
from operator import itemgetter

pets = [('dog',12,2), ('cat',15,1), ('dog',11,1), ('cat',15,2), ('dog',10,3), ('cat',16,3)]

def my_reduce(obj1, obj2):
    return (obj1[0],max(obj1[1],obj2[1]),min(obj1[2],obj2[2]))

解决方案:

print [reduce(my_reduce, group)
       for _, group in groupby(sorted(pets), key=itemgetter(0))]

输出:

[('cat', 16, 1), ('dog', 12, 1)]

这篇关于在python中按键减少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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