如何在python中减少元组列表 [英] How to reduce on a list of tuples in python

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

问题描述

我有一个数组,我想计算数组中每个项目的出现.

I have an array and I want to count the occurrence of each item in the array.

我设法使用了map函数来生成元组列表.

I have managed to use a map function to produce a list of tuples.

def mapper(a):
    return (a, 1)

r = list(map(lambda a: mapper(a), arr));

//output example: 
//(11817685, 1), (2014036792, 1), (2014047115, 1), (11817685, 1)

我期望reduce函数可以帮助我按每个元组中的第一个数字(id)对计数进行分组.例如:

I'm expecting the reduce function can help me to group counts by the first number (id) in each tuple. For example:

(11817685, 2), (2014036792, 1), (2014047115, 1)

我尝试了

cnt = reduce(lambda a, b: a + b, r);

和其他一些方法,但是它们都不能解决问题.

and some other ways but they all don't do the trick.

注意 感谢您提供其他解决问题的方法的建议,但是我只是在这里学习Python以及如何实现map-reduce,并且我已经将我的实际业务问题简化了很多,以使其易于理解,因此,请您多多包涵.告诉我做地图减少的正确方法.

NOTE Thanks for all the advice on other ways to solve the problems, but I'm just learning Python and how to implement a map-reduce here, and I have simplified my real business problem a lot to make it easy to understand, so please kindly show me a correct way of doing map-reduce.

推荐答案

您可以使用Counter:

from collections import Counter
arr = [11817685, 2014036792, 2014047115, 11817685]
counter = Counter(arr)
print zip(counter.keys(), counter.values())

由@ShadowRanger指出Counter具有items()方法:

As pointed by @ShadowRanger Counter has items() method:

from collections import Counter
arr = [11817685, 2014036792, 2014047115, 11817685]
print Counter(arr).items()

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

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