I need help analyzing a list and printing which elements repeat equally in the list. PYTHON

Asked

Viewed 48 times

-2

Serv = [0,1,1,0,9,7]

The most repeated items on the list are 0 and 1, but I couldn’t think of anything I could do to get this.

I tried to fix the first element,:

sound = [2,2,2,2,1,1] and definitely n know how to proceed with this to reach final = [0,1].

 def mais_requisitados(serv):

    final = []
    som = []
    for i in range(0,len(serv),1):
       b = 0
       som.append(b)
    
    for i in serv:
       for j in range(0,len(serv),1):
         if serv[j] == i:
             som[j] += 1

    return print(final)

1 answer

0

You can use a dictionary to store the quantities of each element:

def mais_requisitados(serv):
    dict_count = {}

    for elem in serv:
        # incrementa se a chave já existir
        # marca como 1 se for a primeira vez
        if elem in dict_count:
            dict_count[elem] += 1
        else:
            dict_count[elem] = 1
    # pega o maior valor do contador
    max_elem = max(dict_count.values())
    # cria lista com as chaves que possuem maior valor
    final = [key for key, value in dict_count.items() if value == max_elem]
    return final # [0, 1]
  • Is there any other more trivial way to do it? I haven’t seen a dictionary yet, but if there’s no other way I’ll give a study in a dictionary

  • @Moreira You can also use a list where the index represents the number and value, the amount of times it appears, but this method generates very large lists. On your list serv given as an example [2, 2, 0, 0, 0, 0, 0, 1, 0, 1]. So just take the indexes of the largest element.

Browser other questions tagged

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