“This is the 8th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

Efficient derivation

List derivation

The syntax of a list derivation is very simple, as follows

Generate expression for variable in sequence or iterated object

The outermost square brackets are the symbolic identity of the list. It indicates that the result of the expression is to generate a list, so list comprehensions are called. The list derivation described in square brackets is functionally equivalent to a loop, but in a more concise form.

Let’s use a few more examples to illustrate the power of list comprehensions

1. Filter unqualified elements from the original sequence

In list comprehensions, we can filter the elements that match the criteria by the logic of the if statement. For example, if we want to extract integers from a list and square them,

aList = []
for x in range(4):
    aList.append(x**2)
Copy the code

2. Tiling nested lists using list comprehensions

In the previous list derivation example, we used just one layer of the for loop to generate a new list. In fact, we can also use a two-tier for loop. The following code is an example of tiling a nested list into a list using a two-tier for loop.

Vec = [[1,2,3],[4,5,6],[7,8,9]] flat_vec = [num for elem in vec for num in elem] print(flat_vec)Copy the code

results

,2,3,4,5,6,7,8,9 [1]

In the previous list derivation example, we used just one layer of the for loop to generate a new list. In fact, we can also use a two-tier for loop. The following code is an example of tiling a nested list into a list using a two-tier for loop.

3. A combination of multiple conditions constructs a specific list

As mentioned earlier, list comprehensions consist of a pair of parentheses with an output expression followed by a for statement, followed by zero or more for statements, and then if statements, which can be combined to construct various kinds of higher-order lists. For example, the following list derivation combines elements from two different lists.

New_list = [[x,y] for x in [1,2,3] for y in [3,1,4] if x!=y] print(new-list)Copy the code

results

[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Note that if the expression is a tuple, such as (x,y) at In [12], then parentheses must be used.

4 dictionary derivation

Dictionary derivations are used in a similar way to list derivations, except that the symbol of the list, a pair of square brackets [], is changed to the symbol of the dictionary, a pair of curly brackets {}. For example, the following code swaps the keys and values of an existing dictionary.

mcase = {'a':10,'b':30,'c':50}
kv-exchange = {v: k for  k, v in mcase.items()}
print(kv_exchange)
Copy the code

results

{10:’a’,30:’b’,50:’c’}

In [2] uses the dictionary’s items() method, which returns a traversal enabled list of tuples such as (key 0, value 0) and (key 1, value 2).