Create functions in Python [closed]

-4

I want to create a function that receives a vector of 10 registers, in which each has its name, state (SP or RJ) and age. And then a function to return how many people are of the same state. How could it be done? Thank you.

    
asked by anonymous 03.06.2018 / 03:22

1 answer

0

This example will get a list (of lists) of any size, will associate the variables nome , uf and idade and will add 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 ufs dictionary, updated in the ufs[uf] = ufs.get(uf, 0) + 1 line that retrieves the current value for the state (or zero if it does not exist) and increments by one.

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}

    
03.06.2018 / 16:01