Help with Python cycle

3

Someone could explain to me the process that carries out the following line of code (see the image for more details).

Specifically, this one:

langs = [language for language in languages if language['name'] == name]

I have already tried the code and it is the result that it throws but still I do not understand the line of code itself, because I am not very influential in Python yet, I imagine it is a cycle with a conditional one.

For this reason, I would like you to explain to me what you do step by step and also why the sentence is written in this way, especially the part of language for language , that is if you do not know why it is there.

    
asked by codenoschool 29.07.2017 в 11:40
source

2 answers

4

The following line of code is a summary way to go through, evaluate conditions and load a list

>>> langs = [language for language in languages if language['name'] == name]

Let's analyze the line

  • langs = [] : this is a list declaration
  • language for language in languages if language['name'] == name within the bracket or initialization of the variable, the list languages containing several dictionaries is filtered, those that meet the condition if language['name'] == name] are filtered and finally they are assigned to the list langs
  • language for language : to understand this particular part of the line we must analyze back everything that is within the assignment.

    If we remove language the line would be as follows: for language in languages if language['name'] == name that would otherwise be:

     for language in languages:
         if language['name'] == name:
    

    Then language the portion we remove would equal to:

    langs.append(language)
    

    So the whole line of code in question is equivalent to the following block of code:

    >>> langs = []
    >>> for language in languages:
            if language['name'] == name:
                langs.append(language)
    

    Result: Assuming that the value of the variable name == 'Python'

    >>> print(langs) 
    [{'name': 'Python'}]
    >>> 
    

    The result is the same, but the performance may be different. The code of the summarized form is generally more efficient.

        
    answered by 29.07.2017 / 13:33
    source
    2
    langs = [language for language in languages if language['name'] == name]
    

    This is a fairly simple example of a Python technique and several other languages called list comprehension " (" comprehension of lists "in Spanish) and serves to filter and transform any" iterable ", ie data that can be traversed, such as lists, tuples, dictionaries, just to name the basics. Its syntax could be explained as:

    [expresión de salida] [ciclo] [filtro]
    

    The [filtro] can be optional, the [expresión de salida] can be an element, several or a transformation. In the network you will find a huge amount of examples, as a sample, let's see these cases:

    lista = [1, 2, 3, 4, 5, 6, 7, 8, 9 ]
    # obtengo lo número pares
    print([e for e in lista if e % 2 == 0])
    [2, 4, 6, 8]
    
    # obtengo el cuadrado de cada elemento
    print([e*e for e in lista])
    [1, 4, 9, 16, 25, 36, 49, 64, 81]
    
    # creamos un diccionario enumerando cada elemento
    print({"elemento_{0}".format(i):e for i,e in enumerate(lista, 1)}) 
    {'elemento_1': 1, 'elemento_2': 2, 'elemento_3': 3, 'elemento_4': 4, 'elemento_5': 5, 'elemento_6': 6, 'elemento_7': 7, 'elemento_8': 8, 'elemento_9': 9}
    

    Going back to your example:

    langs = [language for language in languages if language['name'] == name]
    

    The explanation is: a new list langs is initialized with the elements of a list of dictionaries languajes that meet the condition that name == name. That is, we are basically "filtering" the original list into a new one.

        
    answered by 29.07.2017 в 15:33