I have this list
['OE21-k', 'OE28-k', 'OE21-k', 'OE-31-k', 'OE21-k', 'OE21-k', 'OE28-k']
And i want to know, how many OE21-k and how many OE28-k have. Is there any way to sum and calc how many duplicates are there?
I have this list
['OE21-k', 'OE28-k', 'OE21-k', 'OE-31-k', 'OE21-k', 'OE21-k', 'OE28-k']
And i want to know, how many OE21-k and how many OE28-k have. Is there any way to sum and calc how many duplicates are there?
Yes, the collections.Counter
is easy to use:
from collections import Counter
items = ['OE21-k', 'OE28-k', 'OE21-k', 'OE-31-k', 'OE21-k', 'OE21-k', 'OE28-k']
c = Counter(items)
print(c)
Output:
Counter({'OE21-k': 4, 'OE28-k': 2, 'OE-31-k': 1})
If you want to count the occurrences just use the count()
method.
['OE21-k', 'OE28-k', 'OE21-k', 'OE-31-k', 'OE21-k', 'OE21-k', 'OE28-k'].count('OE21-k')
e.g.
occurences = {}
l = ['OE21-k', 'OE28-k', 'OE21-k', 'OE-31-k', 'OE21-k', 'OE21-k', 'OE28-k']
for item in l:
if item not in occurences.keys():
occurences[item] = l.count(item)
occurences = {}
l = ['OE21-k', 'OE28-k', 'OE21-k', 'OE-31-k', 'OE21-k', 'OE21-k', 'OE28-k']
for item in l:
if item in occurences:
occurences[item] += 1
else:
occurences[item] = 1