Search code examples
pythonarrayslist-comprehension

can someone please explain this line of code?


The idea of it is to get any name from nombres that start with any letter that is given by padron and save it into nombres_filtrados (which i can't understand) I would really appreciate the help!

    padron = ['A', 'E', 'J', 'T']

    nombres = ['Tamara', 'Marcelo', 'Martin', 'Juan', 'Alberto', 'Exequiel',
               'Alejandro', 'Leonel', 'Antonio', 'Omar', 'Antonia', 'Amalia',
               'Daniela', 'Sofia', 'Celeste', 'Ramon', 'Jorgelina', 'Anabela', "X"]
   
    nombres_filtrados = [x for x in nombres if any(f in x for f in padron)]

    print(nombres_filtrados)

Thanks!


Solution

  • nombres_filtrados Checks each letter in each name against your padron list, really what it should be is:

    padron = ['A', 'E', 'J', 'T']
    nombres = ['Tamara', 'Marcelo', 'Martin', 'Juan', 'Alberto', 'Exequiel',
           'Alejandro', 'Leonel', 'Antonio', 'Omar', 'Antonia', 'Amalia',
           'Daniela', 'Sofia', 'Celeste', 'Ramon', 'Jorgelina', 'Anabela', "X",'eA']
    
    nombres_filtrados = [x for x in nombres if any(f in x[0] for f in padron)]
    print(nombres_filtrados)
    

    Basically what nombres_filtrados is doing is:

    padron = ['A', 'E', 'J', 'T']
    nombres = ['Tamara', 'Marcelo', 'Martin', 'Juan', 'Alberto', 'Exequiel',
           'Alejandro', 'Leonel', 'Antonio', 'Omar', 'Antonia', 'Amalia',
           'Daniela', 'Sofia', 'Celeste', 'Ramon', 'Jorgelina', 'Anabela', "X",'eA']
    
    nombres_filtrados = [x for x in nombres if any(f in x[0] for f in padron)]
    
    
    output = []
    for name in nombres:        #For Each Name in Nombres
        if name[0] in padron:   #if the First Letter is In Padron
            output.append(name) #Save To Our Output
    
    print(output)