Sort list by frequency in python

0 votes
How do I sort a list by its frequency in Python?

For example, I have the list:

[1,2,3,4,3,3,3,6,7,1,1,9,3,2]
 

The above list would be sorted in the order of the frequency of its values to create the following list, where the item with the greatest frequency is placed at the front:

[3,3,3,3,3,1,1,1,2,2,4,6,7,9]
May 13 in Python by ana1504.k
• 6,710 points
16 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes
You can try the following for a collections.Counter:

counts = collections.Counter(lst)
new_list = sorted(lst, key=lambda x: -counts[x])
 

Alternatively, you could write the second line without a lambda:

counts = collections.Counter(lst)
new_list = sorted(lst, key=counts.get, reverse=True)
answered May 13 by SDeb
• 10,860 points

Related Questions In Python

+1 vote
4 answers

Count the frequency of an item in a python list

To count the number of appearances: from collections ...READ MORE

answered Oct 18, 2018 in Python by tinitales
96 views
+4 votes
7 answers

Splitting a List into chunks in Python

Here's a generator that yields the chunks ...READ MORE

answered Apr 13, 2018 in Python by Nietzsche's daemon
• 4,260 points
2,310 views
0 votes
1 answer

How can I convert a list of dictionaries from a CSV into a JSON object in Python?

You could try using the AST module. ...READ MORE

answered Apr 17, 2018 in Python by anonymous
477 views
+1 vote
3 answers
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
56 views
0 votes
1 answer

In Python, how do I read a file line-by-line into a list?

with open(fname) as f:     content = f.readlines() # you ...READ MORE

answered Oct 9, 2018 in Python by SDeb
• 10,860 points
78 views
0 votes
1 answer

How to Reverse a list in Python

You can use the reversed function in ...READ MORE

answered Sep 28, 2018 in Python by SDeb
• 10,860 points
48 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.