I want to count how many times each item is displaying in a list. Here is what I have:
for i in range(len(alist)):
print(alist[i], alist.count(i))
The issue with this right now is that if the list has for example 7 of the same occurrences, it is printing
a 0
a 0
a 0
a 0
a 0
a 0
a 0
rather than what I want which is
a 7
You could use a collections.Counter
for that:
from collections import Counter
cnt = Counter(['a', 'a', 'b', 'a'])
print(cnt) # Counter({'a': 3, 'b': 1})
Because a Counter
is a dict
underneath, you can then do:
for char, count in cnt.items():
print(char, count)
# a 3
# b 1
You've declared the value of i as an integer, so you need to count the list entry of i, not i itself.
print(alist[i], alist.count(alist[i]))
Alternatively, I'd suggest:
your_list = ['A', 'B', 'A', 'C', 'A']
for item in set(list):
print(f'{item} occurs {your_list.count(item)} number of times.')
This makes your code more readable:) set(list)
will return a set, ie all unique values within the list. Or you can use numpy.unique()
to the same effect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.