To find out how many times a particular value repeats in the list

Asked 2 years ago, Updated 2 years ago, 41 views

For example, list = [1,1,1,1,3,3,7,10]

->1 is 4 ->3 is 2

Is there a function that counts like this?

list python

2022-09-22 15:08

1 Answers

myList =  [1, 2, 3, 4, 1, 4, 1]
print myList.count(1)

3

from collections import Counter
myList =  [1, 2, 3, 4, 1, 4, 1]

print "---Counter()---"
result = Counter(myList)
print result

for key in result:
    print key, result[key]

#If you want to find out the value you counted without a key,
print "---Counter().values()---"
result = Counter(myList).values()
print result

Results are

---Counter()---
Counter({1: 3, 4: 2, 2: 1, 3: 1})
1 3
2 1
3 1
4 2
---Counter().values()---
[3, 1, 1, 2]t


2022-09-22 15:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.