Search code examples
pythonlistsortingnumbersletters

python: how to sort a list of letters and numbers


Such as, lista = [300KB, 12MB, 100KB, 1GB], i want to process lista, then change it to [100KB, 300KB, 12MB, 1GB]

How to sort it using simple method?


Solution

  • "lista" has to be a list of strings. sorted is your friend here. Sorting Mini-HOW TO

    def memory_mult(text):
        memory = {'KB':1024, 'MB':1024**2, 'GB':1024**3}
        num = text[:-2]
        mult = text[-2:]
        return int(num)*memory[mult]
    
    sorted(lista, key=memory_mult)