Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list with duplicate items by the biggest number of duplicate occurrences - Python

Tags:

python

list

I have

list1 = ["one", "two", "two", "three", "five", "five", "five", "six"]

and the output should be

list2 = ["five" , "two", "one", "three" , "six"]
  • "five" is the first element because in list1 has the highest number of occurrences (3)
  • "two" is the second element because in list1 has the next highest number of occurrences (2)
  • "one", "three" and "six" have the same lower number of occurrences (1) so they are last in my list2 - it doesn't really matter what order as long as they are after "five" and "two". list2 = ["five" , "two", "six", "three", "one"] or list2 = ["five" , "two", "three", "one", "six"] or any other variations are acceptable.
like image 432
faceoff Avatar asked Feb 17 '16 14:02

faceoff


1 Answers

You could use a list comprehension and Counter:

from collections import Counter
print([element for element,count in Counter(list1).most_common()])

Outputs:

['five', 'two', 'three', 'six', 'four', 'one']
like image 164
miradulo Avatar answered Nov 14 '22 23:11

miradulo