-4
I want to create a function that receives a vector of 10 records, in which each has name, state (SP or RJ) and age. And then a return function of how many people are from the same state. How could it be done? Thank you.
-4
I want to create a function that receives a vector of 10 records, in which each has name, state (SP or RJ) and age. And then a return function of how many people are from the same state. How could it be done? Thank you.
0
This example will receive a list (of lists) of any size, associate to variables nome
, uf
and idade
and add up the values of uf
:
def conta_ufs(pessoas):
ufs = {}
for pessoa in pessoas:
nome, uf, idade = pessoa
ufs[uf] = ufs.get(uf, 0) + 1
return ufs
lista_de_pessoas = [
['Alexandre', 'AL', 35], ['Larissa', 'BA', 43], ['Carla', 'CE', 25],
['Joaquim', 'CE', 19], ['Nelson', 'RJ', 22], ['Sandra', 'RJ', 39],
['Reinaldo', 'MG', 49], ['Mariana', 'RN', 33], ['Luciano', 'SE', 15],
['Heitor', 'MG', 39]
]
print conta_ufs(lista_de_pessoas)
The total of each state is stored in the dictionary ufs
, updated on line ufs[uf] = ufs.get(uf, 0) + 1
which recovers the current value for the state (or zero if it does not exist) and increments in a.
The end result is a dictionary containing the state acronym and the total occurrences in it:
{'MG': 2, 'BA': 1, 'AL': 1, 'CE': 2, 'SE': 1, 'RN': 1, 'RJ': 2}
As a separate matter nome
and idade
it is possible to take advantage of the loop to perform other operations (average age, greater name etc).
Browser other questions tagged python function
You are not signed in. Login or sign up in order to post.