Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 How to count and order numbers in a list
#1
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
scidam wrote Aug-22-2019, 03:22 AM:
Please post all code, output and errors (in it's entirety) between their respective tags. I did it for you this time, Here are instructions on how to do it yourself next time.
Quote
#2
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})
>>> 
Quote
#3
(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}
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Life of Brian: Conjugate the verb, "to go" !
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  list approach due nested order 3Pinter 6 97 Oct-07-2019, 01:49 PM
Last Post: 3Pinter
  List of numbers to add Planeuge 4 174 Sep-21-2019, 10:41 PM
Last Post: Planeuge
  weird result trying to remove numbers from a list Exsul 6 197 Aug-27-2019, 05:10 AM
Last Post: perfringo
  Count elements in a list only if they are following each other and are similar law 10 385 Aug-02-2019, 10:54 PM
Last Post: law
  removing duplicate numbers from a list calonia 12 818 Jun-16-2019, 12:09 PM
Last Post: DeaD_EyE
  Count the number of items in a nested list iofhua 2 232 Jun-07-2019, 06:47 PM
Last Post: iofhua
  maintaining list order 3Pinter 13 473 Jun-05-2019, 07:49 AM
Last Post: 3Pinter
  huge list of whole numbers Skaperen 3 346 Jun-02-2019, 10:11 PM
Last Post: Skaperen
  count occurrence of numbers in a sequence and return corresponding value python_newbie09 6 394 May-20-2019, 06:33 PM
Last Post: python_newbie09
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 256 May-09-2019, 12:19 PM
Last Post: Pleiades

Forum Jump:


Users browsing this thread: 1 Guest(s)