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
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
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])
> [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.
Easy :
numbers2 = []
for x in numbers :
if not x in numbers :
numbers2.append(x)
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]