How do I print how many times there is a similar term in a python list?

Asked

Viewed 51 times

-1

while True:
    lista = []
    ingresso = (str(input()))
    lista.append(ingresso)
    if ingresso== "FIM":
        break
    elif ingresso != "NORMAL" and ingresso !=  "VIP" and ingresso != "FIM":
        print(f"Comando {ingresso} não existe")

Guys I’m trying to make a program that is to count the number of tickets a vip ticket and another normal if I type wrong something I have to type order later, so far so good, but I also wanted to make it appear at the exit how many tickets Vips and normal were counted I tried to put in a list and use Count() but only the end that goes to the list the end would be to finish the variables of the input how to proceed ?

2 answers

2


Simply put, you could list comprehension

normal = len([n for n in lista if n == 'NORMAL'])
vip = len([v for v in lista if n == 'VIP'])

You can also use the Counter library collections

from collections import Counter

c = Counter(lista)

The Counter returns a dictionary that can be accessed directly by the key. See the example below:

>>> print(c)
Counter({'NORMAL': 15, 'VIP': 2})

>>> print(c['NORMAL'])
15

>>> print(c['VIP'])
2

I hope it helps.

  • thank you very much with some modifications I managed to use the counter in my valeu ai helped demaissss :)

1

I don’t know if I interpreted your problem correctly, but from what I see the error is that you append the ticket before checking the conditions of its existence and you clear the list every time the while loop runs. In case you should use the code this way:

 lista = []
 while True:
     ingresso = (str(input()))
     if ingresso == "FIM":
         lista.append("FIM") #(Opcional)
         break
     elif ingresso != "NORMAL" and ingresso !=  "VIP" and ingresso != "FIM":
         print(f"Comando {ingresso} não existe")
         continue
     lista.append(ingresso)
  • thanks I modified and with the tips of the guy from the top I can finish my code :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.