List count without repeating print - Python

Asked

Viewed 306 times

-4

I’m solving a college list, but I can’t find a way to show the numbers count without repeating the print. For example, when the number is repeated I want to print only once and I am not able to do it, because whatever sweeps the list makes the count appear repeatedly. Follows the code

numero = int(input("Número: "))
freio = 0
l = []

while numero != freio:
    l.append(numero)
    numero = int(input("Número: "))

for x in l:
    if l.count() == 1:
         print("O Número ", x, "aparece", l.count(x), "vez.")
    else:
         print("O Número ", x, "aparece", l.count(x), "vezes.")    

If anyone can help me I’d be grateful.

  • Dei downvote pq I believe that your question is outside the scope of the site (is an example of this case: https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer-perguntas/5486#5486 ). As always, I am willing to reevaluate my vote in the face of a reformulation. Abs,

1 answer

1

You can use the Python Collections Counter, which will count the elements for you:

from collections import Counter

numero = int(input("Número: "))
freio = 0
l = []

while numero != freio:
  l.append(numero)
  numero = int(input("Número: "))

#Transforma sua lista já efetuando a contagem dos itens repetidos
counter = Counter(l)

for x in counter:
  if counter[x] == 1:
    print("O Número", x, "aparece", counter[x], "vez.")
  else:
    print("O Número", x, "aparece", counter[x], "vezes.")

See online: https://repl.it/repls/GrownBlushingIntegrationtesting


It is also possible to turn your list into a dictionary, the number being the dictionary key and the value the count:

numero = int(input("Número: "))
freio = 0
l = []

while numero != freio:
  l.append(numero)
  numero = int(input("Número: "))

#Cria um dicionário com base na lista
d = {x:l.count(x) for x in l}

for x in d:
  if d[x] == 1:
    print("O Número", x, "aparece", d[x], "vez.")
  else:
    print("O Número", x, "aparece", d[x], "vezes.")

See online: https://repl.it/repls/ImaginativeLightpinkScan

Browser other questions tagged

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