So I wanted to write a program that would print out how many times a number is repeated in a list. I'm very new to Python and I used the .count() command to get the number of times an element is repeated. I want the output to follow the format "The number n is repeated n times".
This is what I have so far:
x = [1,1,2,4,5,7,2,3,3,8,2,3,6,7]
index = 0
while index < len(x):
print('The number {} is repeated {} times.'.format(x[index],x.count(x[index])))
index = index + 1
And this is the output:
The number 1 is repeated 2 times
The number 1 is repeated 2 times
The number 2 is repeated 3 times
The number 4 is repeated 1 times
The number 5 is repeated 1 times
The number 7 is repeated 2 times
The number 2 is repeated 3 times
The number 3 is repeated 3 times
The number 3 is repeated 3 times
The number 8 is repeated 1 times
The number 2 is repeated 3 times
The number 3 is repeated 3 times
The number 6 is repeated 1 times
The number 7 is repeated 2 times
I want the output to show how many times a number is repeated only once, and in ascending order. How can I make the output come out like this:
The number 1 is repeated 2 times.
The number 2 is repeated 3 times.
The number 3 is repeated 3 times.
...
Thank you! :)
This counts all occurrences of numbers and prints them in ascending order.
from collections import Counter
x = [1, 1, 2, 4, 5, 7, 2, 3, 3, 8, 2, 3, 6, 7]
for key, val in sorted(Counter(x).items()):
print(f'The number {key} is repeated {val} times.')
Code Output:
The number 1 is repeated 2 times.
The number 2 is repeated 3 times.
The number 3 is repeated 3 times.
The number 4 is repeated 1 times.
The number 5 is repeated 1 times.
The number 6 is repeated 1 times.
The number 7 is repeated 2 times.
The number 8 is repeated 1 times.