How to count and order numbers in a list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to count and order numbers in a list (/thread-20598.html) |
How to count and order numbers in a list - rachyioli - Aug-21-2019 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+=1and this is what I get : 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 RE: How to count and order numbers in a list - buran - Aug-21-2019 https://docs.python.org/3.7/library/collections.html#collections.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}) >>> RE: How to count and order numbers in a list - perfringo - Aug-21-2019 (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} |