-1

I need a list like this one

numbers = [1,1,1,1,1,1,6,6,6,6,6,3,3,3,3,2,2,2,4,4,5]

to get to this:

[1, 6, 3, 2, 4, 5]

Not sure how to write the code in python, can anyone help

  • Do you need to maintain that same order? If not, `list(set(numbers))` gives your desired output. – ddejohn Apr 11 '21 at 14:54
  • Also what does your code have to do with your title? – ddejohn Apr 11 '21 at 14:55
  • `{}.fromkeys(numbers).keys()` will unify only. `[t[0] for t in sorted(Counter(numbers).items(), key=lambda t: t[1])]` will 'sort' in most common to least common. – dawg Apr 11 '21 at 14:59
  • https://stackoverflow.com/questions/50372558/clean-txt-and-count-most-frequent-words https://stackoverflow.com/questions/42879739/counting-the-most-frequent-word-in-a-list https://stackoverflow.com/questions/53706595/python-pandas-count-most-frequent-occurrences https://stackoverflow.com/questions/63041687/find-the-most-frequent-words-that-appear-in-the-dataset https://stackoverflow.com/questions/47251934/how-to-count-the-most-frequent-letter-in-a-string (and this is not an exhaustive list) This seems like you could have searched first – DavidW Apr 11 '21 at 15:02

4 Answers4

0

The built-in Counter module can help with this problem: https://docs.python.org/3/library/collections.html#collections.Counter.most_common

from collections import Counter

nums_and_freqs = Counter(numbers).most_common(6)
print([num for num, _ in nums_and_freqs])
Anson Miu
  • 1,171
  • 7
  • 6
0
> [k for k,c in sorted([(k,len(list(it))) for k, it in groupby(sorted(a))], key=lambda x: x[1], reverse=True)]

[1, 6, 3, 2, 4, 5]

sort and group the keys, then count and sort by count, finally just extract the keys.

karakfa
  • 66,216
  • 7
  • 41
  • 56
0

Easy :

numbers2 = []
for x in numbers :
    if not x in numbers :
        numbers2.append(x)
Tom Kuntz
  • 55
  • 1
  • 7
0

If you want a list to be uniqueified and sorted from most common to least common:

numbers = [1,6,6,6,6,6,3,3,3,3,2,2,2,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5]
from collections import Counter 

>>> [t[0] for t in sorted(Counter(numbers).items(), key=lambda t: -t[1])]
[5, 6, 3, 2, 4, 1]

If you only want the list uniquified but left in order:

numbers = [1,1,1,1,1,1,6,6,6,6,6,3,3,3,3,2,2,2,4,4,5]

>>> list({}.fromkeys(numbers).keys())
[1, 6, 3, 2, 4, 5]
dawg
  • 98,345
  • 23
  • 131
  • 206