Count occurrences in tuples

1

I have a problem that is simple but I am not getting the solution.

I have a list of tuples, for example:

lista = [('x',2,3),('y',4,5),('x',6,7),('z',8,9)]

What I want is for him to tell me how many times x , y and z appear in this list. In this case, x appears 2 times and y and z appear 1 , so should return a list with [2,1,1] .

And I wanted to resolve this with map or reduce .

    
asked by anonymous 13.04.2016 / 19:23

2 answers

1

You can use the excellent Counter of collections :

from collections import Counter
lista_contagens = Counter(map(lambda: x, x[0], lista))
# Isto imprime as contagens
print(lista_contagens.values())
    
13.04.2016 / 19:47
1

Word count is the basic example of map / reduce. For this case, just adapt to the map stage and implement the traditional reduce. Here is an example for mapper:

mapper.py

lista = [('x',2,3),('y',4,5),('x',6,7),('z',8,9)]
for i in lista:
    print '%s\t%s' % (i[0], '1')

Following is a complete sample documentation: link

    
13.04.2016 / 19:46