Python Arrays Minimize Values

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

2 answers

  • answered 2022-01-23 02:57 Raymond Kwok

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

  • answered 2022-01-23 03:07 Mateen Ulhaq

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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum