How to point the oldest person on a list?

Asked

Viewed 43 times

-1

Good afternoon everyone, I have a question about my Python studies.

According to the proposed exercise, I should create a list scheme within a larger list where a name and age will be recorded sequentially. Once that’s done, I should point out who the older person is but I’m having trouble trying to solve it.

dados = list()
listac = list()
maior = list()
cont = 0
while True:
   print('_'*15)
   dados.append(str(input('Nome: ')))
   dados.append((int(input('Idade: '))))
   listac.append(dados[:])
   dados.clear()
   cont += 1
   if cont == 3:
       break
print()
print(listac)
print()
for a in listac:
   print(f'{a[0]} tem {a[1]} anos de idade.')
print(listac)
  • what is the problem? can you give a brief explanation? what is going wrong? what is your question, specifically?

  • I can’t pinpoint the age of the older person within this exercise. I tried using max and min, but it doesn’t work.

  • With the code, I can so far create a list to receive names and their ages, and each name and age are divided into lists. Ex: [ [Jean, 27], [Jonas, 25], [Caio, 13]. Three lists within one. What I can do so far is pull the indexes, the names and the ages. Ex: print(listac[0][0] that will return Jean.

1 answer

1

You must first order your field Idade using Descending to then make your loop.

class Pessoa(object):
    def __init__(self, nome: str, idade: int):
        self.Nome = nome
        self.Idade = idade

dados = list()
listac = list()
maior = list()
cont = 0
while cont < 3:
   print('_'*15)
   nome = str(input('Nome: '))
   idade = int(input('Idade: '))
   pessoa = Pessoa(nome, idade)
   listac.append(pessoa)
   cont += 1
print()


listac.sort(key=lambda x: x.Idade, reverse=True)
print(listac, end='\n\n')

for a in listac:
   print(f'{a.Nome} tem {a.Idade} anos de idade.')
print(listac)

if you need the first simply access index 0

pessoa = listac[0]
print(f'{pessoa .Nome} tem {pessoa .Idade} anos de idade.')

Browser other questions tagged

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