+ 3
Counting similar elements
How to count some repeating (duplicate) elements in a list?
5 Respuestas
+ 5
There's probably a million ways to do this, but I would do something like this:
from random import randint
# create a list with repeated elements
l = [randint(1, 10) for i in range(20)]
# sample output: [9, 10, 5, 9, 10, 10, 1, 2, 9, 3, 5, 9, 9, 9, 6, 5, 4, 5, 7, 10]
# create a set with the unique elements in the list
s = set(l)
# sample output: {1, 2, 3, 4, 5, 6, 7, 9, 10}
# create a dictionary with the single elements and their count
c = {item: l.count(item) for item in s}
print(c)
# sample output: {1: 1, 2: 1, 3: 1, 4: 1, 5: 4, 6: 1, 7: 1, 9: 6, 10: 4}
If you only want repeated elements:
c = {item: l.count(item) for item in s if l.count(item) > 1}
print(c)
# sample output: {5: 4, 9: 6, 10: 4}
If you want to use a predefined module, you can use collections.Counter:
from collections import Counter
from random import randint
l = [randint(1, 10) for i in range(20)]
print(Counter(l))
# sample output: Counter({9: 6, 10: 4, 5: 4, 1: 1, 2: 1, 3: 1, 6: 1, 4: 1, 7: 1})
+ 4
Anna 👍👍
+ 3
Anna thank you.....can we use nested for loop?
count=0
For i in list:
For j in list:
If i==j:
count = count+1
Why this code not giving right answer?
+ 3
You probably could use a nested for loop, but it's unnecessarily complicated in my opinion because you have to make sure that the items aren't compared to themselves:
l = [1, 2] # list without duplicates
for i in l:
for j in l:
print(i, j)
# result:
1 1 # looks like a duplicate
1 2
2 1
2 2 # looks like a duplicate
This works a bit better, but it's still not correct:
l = [1, 2, 2] # list with one repeated element
for i in range(len(l)):
for j in range(len(l)):
if i == j:
continue # make sure that items are not compared to themselves
if l[i] == l[j]:
print('found duplicate:', l[i])
# output:
found duplicate: 2
found duplicate: 2 # still wrong: duplicate found, but counted twice
+ 2
your_list.count('that element')