pythonlistcountmax

make a list according to max count


I have a list

my_list = [3,8,11,8,3,2,1,2,3,3,2] # my list

max(my_list, key=my_list.count)  # most frequent number appeared on the list

But i want to make a list according to the most frequent number appeared on the list. How can i do it?

For example new list output will be:

new_list = [3, 2, 8, 1, 11]  # new list according to the most frequent number appeared.

As 3 came 4 times, 2 came 3 times,8 and 2 came twice and 1,11 came once.


Solution

  • Using collections.Counter:

    from collections import Counter
    
    xs = [3, 8, 11, 8, 3, 2, 1, 2, 3, 3, 2]
    xs_by_count = [k for k, count in Counter(xs).most_common()]
    print(xs_by_count)