Reputation: 15
I am trying to change the values of an array into smaller numbers like
list = [1,3,7,3]
into
list = [1,2,3,2]
I already have a few lines of code to keep it organized.
def sortItems(list):
counts = collections.Counter(list)
sortedlist = sorted(list, key=counts.get, reverse=True)
return sortedlist
been crawling all over W3Schools and other forums but still unsure
Upvotes: 0
Views: 115
Reputation: 2541
l = [1, 3, 7, 3]
unique_keys = set(l)
mappings = {key: val for val, key in enumerate(sorted(unique_keys), 1)}
print(list(map(mappings.get, l)))
Orders are preserved by the sorted()
.
Upvotes: 3
Reputation: 27201
(This answer addresses the information in the comments.)
For a performant implementation, count, sort keys, then repeat and flatmap.
from collections import Counter
from itertools import repeat
def flatmap_repeat_sort_count(xs):
counts = Counter(xs)
keys = sorted(counts.keys())
return [
x
for i, k in enumerate(keys, start=1)
for x in repeat(i, counts[k])
]
Example runs:
>>> flatmap_repeat_sort_count([1, 3, 7, 3])
[1, 2, 2, 3]
>>> flatmap_repeat_sort_count([7, 1, 3, 1])
[1, 1, 2, 3]
Upvotes: 0