11
I have a list
with the following values:
numeros = [5, 3, 1, 2, 3, 4, 5, 5, 5]
In Python would have some function to count how many times some value repeats?
For example: I want to know how many times the 5
repeated.
11
I have a list
with the following values:
numeros = [5, 3, 1, 2, 3, 4, 5, 5, 5]
In Python would have some function to count how many times some value repeats?
For example: I want to know how many times the 5
repeated.
15
Only use the method count()
numeros = [5, 3, 1, 2, 3, 4, 5, 5, 5]
numeros.count(5)
15
You can use the Counter
:
import collections
numeros = [5, 3, 1, 2, 3, 4, 5, 5, 5]
repetidos = collections.Counter(numeros)
print(repetidos[5])
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
If you prefer the short form:
print(collections.Counter([5, 3, 1, 2, 3, 4, 5, 5, 5])[5])
Bacana, the Counter
returns a structure similar to a dict
with key value assignment...
I believe this should be the accepted answer, as it is much more general than the @LINQ response
@Luizangioletti "much more general" refers to being able to iterate and take the amount of repetitions of each? (This seems to me the only difference of both)
@Luizangioletti, maybe the case of the AP is just to count a single el specific number and then he will forget the collection. In that case, the LINQ response will be more appropriate than that. If it is necessary to make multiple counts there is strategy adds much more than the other
Browser other questions tagged python list
You are not signed in. Login or sign up in order to post.
In Python 2.7 it also worked :p
– Wallace Maxters
Yes. I just saw that it works for both
– Jéf Bueno
Jeez, minimalist! Python ♥
– Guilherme Nascimento