Compare the widget with the rest of the Python list

Asked

Viewed 211 times

0

I need to create a program where in the given list, if the name is repeated it puts a numbering. For example: names = [maria, Joao, maria] the result should be result = [maria, Joao, maria1]

Other example: names = [Eduardo, Joao, Eduardo, Eduardo] result = [Eduardo, Joao, eduardo1, eduardo2]

I put together a code that compares with the next name, I don’t know how to continue the comparison.

follows my code:

inserir a descrição da imagem aqui

  • 1

    Welcome Tatiane, you can be more specific? Edith the question and give some practical example or put part of your code.

3 answers

0

You can use a dictionary to save how many times a name has appeared.

names = ['eduardo', 'joao', 'eduardo', 'eduardo', 'joao']

d = {}

for i in range(len(names)):
    if names[i] in d:
        d[names[i]] += 1
        names[i] += str(d[names[i]])
    else:
        d[names[i]] = 0

0

With Dictionary it is possible to store the names and the number of times you repeat:

    def usernamesSystem(u):
        cont = 0
        aDict = {}
        result = []
        for i in range(len(u)):
            cont = checkKey(aDict, u[i]) # verifica o numero de ocorrencia do nome
            if cont == 0:
                aDict[u[i]] = 1 # primeira ocorrencia, guarda valor 1 no dictionary
                result.append(u[i]) # carrega o array de output com a palavra 
            else:
                aDict.update({u[i]: cont + 1 }) # atualiza as ocorrencias do nome no dictionary
                result.append(u[i] + str(cont)) # carrega o array de output com o nome concatenado com o numero de vezes repetido
        return result # array de output com o resultado

    def checkKey(dict, key): 
        if key in dict.keys(): 
            return dict[key] # retorna o numero de ocorrencias quando ja existe no dictionary
        else: 
            return 0 # retorna 0 se não existir

0

I now put the most complete answer, with the class I used.

class Usernames:

    @staticmethod
    def usernamesSystem(u):
        cont = 0
        aDict = {}
        result = []
        for i in range(len(u)):
            cont = Usernames.checkKey(aDict, u[i])
            if cont == 0:
                aDict[u[i]] = 1
                result.append(u[i])
            else:
                aDict.update({u[i]: cont + 1 })
                result.append(u[i] + str(cont))
        return result

    @staticmethod
    def checkKey(dict, key): 
        if key in dict.keys(): 
            return dict[key] 
        else: 
            return 0

nomes = ['eduardo', 'joao', 'eduardo', 'eduardo']
print(Usernames.usernamesSystem(nomes))
  • Thank you so much! it worked!!!!

  • Good. Don’t forget to give feedback (vote).

Browser other questions tagged

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