[Python] How do I get an item in a list to print only once, while counting the same number of...

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    cart = ["pizza", "pizza", "pizza", "soda", "soda", "pretzel"]

    for i in cart:
    item_count = cart.count(i)
    if cart.count(i) > 1:
    print(f"{i}({item_count})")
    else:
    print(i)


    output:

    pizza(3) pizza(3) pizza(3) soda(2) soda(2) pretzel

    Instead, I want the output to look like this:

    pizza(3) soda(2) pretzel

    So, if it's one item it prints the item only, but if it's more than 1 item, it prints the item once plus the quantity in parenthesis. I know it has something to do with the for loop, but I'm not sure how to get it to print outside the for loop with the item and quantity next to it.

    Continue reading...

Compartilhe esta Página