[Python] Python3: Count the occurrences in a list and sort it descendant

Discussão em 'Python' iniciado por Stack, Abril 18, 2025.

  1. Stack

    Stack Membro Participativo

    I have a working code but, I am looking to learn a more pythonic version as I feel my code is very clunky.

    The ideia is to count the number of occurrences in a list ("Names") and sort it descendant.

    aux_list = []
    names = ["Jessica", "John", "Steve", "John", "John", "Steve"]
    total = {}

    for name in names:

    if name is not aux_list:
    aux_list.append(name)

    count = names.count(name)
    key = { name : count }
    total.update(key)

    # sort desc
    sorted_total = sorted(total, key=total.get, reverse=True)

    # Desired output: <NAME> <TOTAL> DESC ORDER
    # John 3
    # Steve 2
    # Jessica 1

    for r in sorted_total:
    print(r, total[r])

    Continue reading...

Compartilhe esta Página