Get how many times each element of a list repeats

Asked

Viewed 176 times

-1

I have the following array:

CLIENTE = ['MARIA','JOAO','MARIA','JOAO']

I’d like to do the following:

{'MARIA' : 2, 'JOAO': 2}

I tried to use the library from collections import Counter, but made a Count in each letter of the array.

  • What do you mean "in every letter"? Could you show exactly how you did it? It makes no sense to consider the letters separately.

  • I believe this is why the array is populated by a select in the database

  • Luis, the Counter will only count each letter if you pass a string. If you pass the list directly, it doesn’t happen, regardless of where the list was generated

2 answers

2

I don’t know how you used the Counter, but it does work. Just pass the list directly to it:

from collections import Counter

clientes = [ 'MARIA', 'JOAO', 'MARIA', 'JOAO' ]
counter = Counter(clientes)
print(counter)

Exit:

Counter({'MARIA': 2, 'JOAO': 2})

And as I said in another question of yours, try to give more meaningful names to variables. If it is a multi-client list, it is better to call clientes (plural, suggests that it has more than one), instead of CLIENTE (singular, implies that it refers to only one). It may seem like a minor detail, but better names help a lot when programming.

1


Just run the following code:

import collections

CLIENTE = ['MARIA','JOAO','MARIA','JOAO']
resultado = collections.Counter(CLIENTE)
print(resultado)

working example

  • 2

    Philip, why did you convert the result to dict?

  • @Andersoncarloswoss, because otherwise it will return a Counter type and not a dictionary, as requested in the question.

  • 2

    Good, Counter is a subclass of dict, then by definition itself is already a dict:D

  • @Andersoncarloswoss truth, edited response, thanks for the touch (:

Browser other questions tagged

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