Find repeated values in a list and insert another value in its place with Python

Asked

Viewed 53 times

-2

I have a list that contains other lists with details of name, age and height of several people:

pessoas = [['PAULO', 75, 1.74], ['ANDRE', 15, 1.87], ['PEDRO', 26, 1.46], ['JULIO', 75, 1.78], ['PAULO', 84, 1.88], ['JOÃO', 34, 1.56], ['SERGIO', 88, 1.74]]

Done that, I created a for to find people with repeated names. If he finds an equal name, he compares age. If that person with the same name is older, it replaces the age and height of that person with the same name, thus creating a new list (l). That is, I do not want repeated names on the list. If there is, it leaves in the new list the person who is older, with their respective age.

That was my code:

l = []
for i in pessoas:
    if pessoas[i][0] not in l: #SE NÃO TIVER NENHUMA PESSOA COM ESSE NOME, É INSERIDO OS DADOS DA PRIMEIRA PESSOA
        l.append(i)
    else:
        idadeindex = l.index(pessoas[i][0]) #SE JÁ TIVER ESSE NOME, Ó CÓDIGO PROCURA O INDEX DO NOME QUE JA ESTA DENTRO DA LISTA
        if l[idadeindex][1] < pessoas[i][1]: #SE A IDADE DE QUEM ESTA DENTRO DA LISTA FOR MENOR DA PESSOA QUE ESTÁ FORA
            l[idadeindex][1] = pessoas[i][1] #POR FIM, ELE SUBSTITUI A IDADE E A ALTURA, MATENDO O NOME
            l[idadeindex][2] = pessoas[i][2]
print(l)

He returns that mistake:

TypeError: list indices must be integers or slices, not list

I’m new to Python and can’t get my code to work. Can anyone think of an easier way to do that?

1 answer

0

This error is being generated because you are scrolling through each list in your list list and trying to use it as an index, which should be an integer.

What you certainly wanted to do is:

for i in range(len(pessoas)):
    # Código...

To check if the names already exist in the list, the ideal would be to use a dictionary. Thus, it would no longer be necessary to search by index, but by name. See the code below:

pessoas_filtradas = {}

for pessoa in pessoas:
    if not pessoa[0] in pessoas_filtradas:
        # Aqui ele adiciona apenas [altura, peso] porque o
        # nome já é registrado como chave.
        pessoas_filtradas[pessoa[0]] = pessoa[1:]
    else:
        if pessoas_filtradas[pessoa[0]][0] < pessoa[1]:
            pessoas_filtradas[pessoa[0]] = pessoa[1:]
  • Complementing... If you want the list answer as the original, do it nova_lista = [[k]+v for k, v in pessoas_filtradas.items()]

Browser other questions tagged

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