Python Forum

Full Version: How to count and order numbers in a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys, I have a list of random numbers and I want to know how many times each number occurs on the list ; I want them ordered by the ones that occurred the most first.
This is my program :
lex=(1,2,3,4,5,6,1,2,3,3,3)
x=0
for i in range(7):
	print(x," appeared  ", lex.count(i))
	x+=1
and this is what I get :
Output:
0 is 0 1 is 2 2 is 2 3 is 4 4 is 1 5 is 1 6 is 1
what I need now is to order them from the ones that happened the most in the list: In this case 3 should be at the top because it happened four times ...
is there a way I can use two functions at the same time in this loop.
thanks
https://docs.python.org/3.7/library/coll...ns.Counter

>>> from collections import Counter
>>> spam = Counter((1,2,3,4,5,6,1,2,3,3,3))
>>> spam
Counter({3: 4, 1: 2, 2: 2, 4: 1, 5: 1, 6: 1})
>>> 
(Aug-21-2019, 10:22 AM)rachyioli Wrote: [ -> ]what I need now is to order them from the ones that happened the most in the list

You can extend solution provided by buran with .most_common method. If you want regular dict you can convert:

>>> spam.most_common(len(spam.keys()))
[(3, 4), (1, 2), (2, 2), (4, 1), (5, 1), (6, 1)]
>>> dict(spam.most_common(len(spam.keys())))
{3: 4, 1: 2, 2: 2, 4: 1, 5: 1, 6: 1}