-1

I have a list

list1 = [4,6,2,2,2,6,4,4,4]

I want to sort it based on the frequency of its elements.

After sorting the list should look like:

[4,4,4,4,2,2,2,6,6]

I have stored the element and element frequency in a dictionary. I want to sort this dictionary acc. to its value and not key. This is the part i am not able to code.

I have written the following code. I have the frequency of the elements but i dont know how to sort it.

def checkio(data):

    list1 = [4,6,2,2,2,6,4,4,4]
    list2 = list(dict.fromkeys(list1))
    print(list2)
    d = {}
    list4, result = [], []

    for i in list2:
        d[i] = list1.count(i)

    for i in list2:
        list3 = [i]*d[i]
        list4.append(list3)
    for sublist in list4:
        for item in sublist:
            result.append(item)

    return(result)

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
Kunal Jain
  • 41
  • 6
  • just `sorted(list1, key=list1.count, reverse=True)` – 1v3m Apr 28 '19 at 12:19
  • 1
    @1v3m This is a very inefficient solution, see the solution you posted yourself as a duplicate – Olivier Melançon Apr 28 '19 at 12:22
  • for efficient and native way you can check [this](https://gist.github.com/CyberSaxosTiGER/6e4276c3128c7e1f47abe723207da5c7), I can't post it because question is closed – 1v3m Apr 28 '19 at 12:42

1 Answers1

1

The short answer is in the comment, which has a small performance drawback, though. You can also use collections.Counter:

import collections

list1 = [4,6,2,2,2,6,4,4,4]
c = collections.Counter(list1)
sorted_list1 = sorted(list1, key=lambda k: c[k], reverse=True)

This counts all elements just once, which gives better performance on very large lists.

user2722968
  • 13,636
  • 2
  • 46
  • 67
  • Thank you! But Py.CheckiO( the site from which i am doing this problem) does not support collections. Also, could you please explain me the lambda function?Thanks – Kunal Jain Apr 28 '19 at 12:30
  • @KunalJain instead of asking about what lambda does, you should read through the Python tutorial and learn the language https://docs.python.org/3/tutorial/ – Boris Verkhovskiy Apr 28 '19 at 12:38
  • Then go with `key=list1.count`. The `sorted`-function will call this method for every item it encounters, so every item accesses the entire list in order to count it; this is where performance suffers. The lambda-function is shorthand as `sorted` will call the function given via `key` with exactly one parameter, the item being sorted. The lambda function retrieves the pre-computed number of occurences from the `Counter`-object. – user2722968 Apr 28 '19 at 12:43