如何在python中减少元组列表

Lee*_*Lee 2 python mapreduce python-2.7

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

我已经设法使用地图功能来产生元组列表。

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

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

//output example: 
//(11817685, 1), (2014036792, 1), (2014047115, 1), (11817685, 1)
Run Code Online (Sandbox Code Playgroud)

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

(11817685, 2), (2014036792, 1), (2014047115, 1)
Run Code Online (Sandbox Code Playgroud)

我试过了

cnt = reduce(lambda a, b: a + b, r);
Run Code Online (Sandbox Code Playgroud)

和其他一些方法,但是他们都无法解决问题。

注意 感谢您提供有关解决问题的其他方法的所有建议,但是我只是在学习Python以及如何在此处实现map-reduce,并且为了使您易于理解,我对我的实际业务问题进行了很多简化,所以请请向我展示进行map-reduce的正确方法。

sco*_*ope 5

您可以使用Counter

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

编辑:

正如@ShadowRanger所指出的那样,它Counter具有以下items()方法:

from collections import Counter
arr = [11817685, 2014036792, 2014047115, 11817685]
print Counter(arr).items()
Run Code Online (Sandbox Code Playgroud)