0

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

6
  • What is the logic you want, why 7 becomes 3? Is it because it is the third biggest value? Commented Jan 23, 2022 at 2:53
  • yes. I am trying to change it so that 1 will become 1 3 will become 2 and 7 will become 3. Commented Jan 23, 2022 at 2:55
  • What should [7, 1, 3, 1] become? Commented Jan 23, 2022 at 2:56
  • It should become ``` [3,1,2,1] ``` but the sorting function will change it to ``` [1,1,2,3] ``` Commented Jan 23, 2022 at 2:58
  • 2
    "crawling all over W3Schools" - That explains it :-P Commented Jan 23, 2022 at 3:12

2 Answers 2

3
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().

Sign up to request clarification or add additional context in comments.

3 Comments

yes, I have changed that.
oh sorry, I misunderstood. You are right! It will be better with enumerate(..., 1).
Or with pandas: pd.Series(mylist).rank(method='dense').to_list()
0

(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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.