1

I have to write all the elements separately along with their count. It's the program i have made. It is counting correctly but not giving required output

The output is like this I want output to be like this. All digits showing individual complete count

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    In StackOverflow we don't put images of code, could you please paste your code here and mark it as `code` so that the syntax highlighter does its job. – fpopic Nov 21 '19 at 19:55
  • Does this answer your question? [How to count the frequency of the elements in an unordered list?](https://stackoverflow.com/questions/2161752/how-to-count-the-frequency-of-the-elements-in-an-unordered-list) – Karl Knechtel Jul 28 '22 at 03:34

1 Answers1

2

You can count the number of occurrence of a special element with count() method:

grades = ['b', 'b', 'f', 'c', 'b', 'a', 'a', 'd', 'c', 'd', 'a', 'a', 'b']
letters = ['a', 'b', 'c', 'd', 'f']

print(list(map(lambda letter: {letter: grades.count(letter)}, letters)))

Output:

[{'a': 4}, {'b': 4}, {'c': 2}, {'d': 2}, {'f': 1}]

If you want to do this without using letters. you can do this:

grades = ['b', 'b', 'f', 'c', 'b', 'a', 'a', 'd', 'c', 'd', 'a', 'a', 'b']

print(list(map(lambda letter: {letter: grades.count(letter)}, set(grades))))

Output:

[{'f': 1}, {'b': 4}, {'c': 2}, {'d': 2}, {'a': 4}]

For your expected output:

grades = ['b', 'b', 'f', 'c', 'b', 'a', 'a', 'd', 'c', 'd', 'a', 'a', 'b']

occurrence = map(lambda letter: (letter, grades.count(letter)), set(grades))

for item in occurrence:
    print(f"{item[0]}={item[1]}")

Output:

c=2
b=4
d=2
f=1
a=4

Update

You can use defaultdict() to count the occurrence of each element:

from collections import defaultdict

grades = ['b', 'b', 'f', 'c', 'b', 'a', 'a', 'd', 'c', 'd', 'a', 'a', 'b']
occurrence = defaultdict(lambda: 0)

for character in grades:
    occurrence[character] += 1

for key, value in occurrence.items():
    print(f"{key}={value}")

Output:

b=4
f=1
c=2
a=4
d=2
Community
  • 1
  • 1
Phoenix
  • 3,996
  • 4
  • 29
  • 40