Python: count repeated elements in the list
You can do that using count
:
my_dict = {i:MyList.count(i) for i in MyList}
>>> print my_dict #or print(my_dict) in python-3.x
{'a': 3, 'c': 3, 'b': 1}
Or using collections.Counter
:
from collections import Counter
a = dict(Counter(MyList))
>>> print a #or print(a) in python-3.x
{'a': 3, 'c': 3, 'b': 1}
How do I count the occurrences of a list item?
If you only want a single item's count, use the count
method:
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
Important: this is very slow if you are counting multiple different items
Each count
call goes over the entire list of n
elements. Calling count
in a loop n
times means n * n
total checks, which can be catastrophic for performance.
If you want to count multiple items, use Counter
, which only does n
total checks.
How to count the frequency of the elements in an unordered list?
If the list is sorted, you can use groupby
from the itertools
standard library (if it isn't, you can just sort it first, although this takes O(n lg n) time):
from itertools import groupby
a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
[len(list(group)) for key, group in groupby(sorted(a))]
Output:
[4, 4, 2, 1, 2]
How can I get a count of repeated elements in a Python list?
Solved!
I used itertools
here's the code:
list4=[]
a = [list(g) for k, g in itertools.groupby(lista)]
for i in range(len(a)):
if 0 in a[i]:
list4.append([0,len(a[i]),i])
elif 1 in a[i]:
list4.append([1,len(a[i]),i])
Count adjacent repeated elements in the list
Your code is not accounting for the last item in the list because you are avoiding an index out-of-bound error in the evaluation of lst[index] == lst[index+1]
by iterating over a range of one less than the length of the list with while(index < len(lst)-1):
.
An easy workaround without having to duplicate the counting code after the loop is to unconditionally append a dummy item to the list first, and optionally pop it after the counting is done, if you still need the original list intact. The example below uses an instance of object
as a dummy item because it helps make sure that the last evaluation of lst[index] == lst[index+1]
would never be True
:
lst.append(object()) # append a dummy item first
while(index < len(lst)-1):
count = 1
result.append(lst[index])
while(lst[index] == lst[index+1]):
count += 1
index += 1
result.append(str(count))
index += 1
print("step: ", result)
lst.pop() # add this line only if you still need the original lst for later use
Trying to get a count of duplicate elements
If the Count is greater than one, check if a
is not in the dup
list, then add a
to it.
Finally, print the length of the dup
list
n=int(input("Enter the number of products to be stored in a list : "))
list1=[]
for i in range(n):
item = int(input("value for product " + str(i+1) + " : "))
list1.append(item)
dup = []
for a in list1:
if (list1.count(a) > 1) and (a not in dup):
dup.append(a)
print("Count of duplicate elements in the list: ", len(dup))
Related Topics
Which Is the Easiest Way to Simulate Keyboard and Mouse on Python
Parsing Datetime Strings Containing Nanoseconds
Libxml Install Error Using Pip
How to Format a String Using a Dictionary in Python-3.X
How to Plot Multiple Functions on the Same Figure, in Matplotlib
How to Create a Custom Activation Function with Keras
Function Changes List Values and Not Variable Values in Python
Django Rest Framework File Upload
Trying to Import Module with the Same Name as a Built-In Module Causes an Import Error
Oserror [Errno 22] Invalid Argument When Use Open() in Python
Pycharm Doesn't Recognise Installed Module
Installing Pip Packages to $Home Folder
Custom Filter in Django Admin on Django 1.3 or Below
Check If Item Is in an Array/List
Prime Number Check Acts Strange
How to Send Cookies in a Post Request with the Python Requests Library