Count occurrences in tuples

Asked

Viewed 281 times

1

I have a problem that is simple but I’m 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 on that list. In this case the x appears 2 times and the y and z appear 1 time, soon should return me a list with [2,1,1].

And I wanted to settle this with map or reduce.

2 answers

1

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())
  • the x inside the lambda represents what? Tells me it is not set

  • I already solved it, it was : lista_contagens = Counter(map(lambda x: x[0], lista)) but this does not return me the list as I wanted: [2,1,1]

  • I updated the answer.

  • That’s right, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.