Python's concise and elegant derivation example

  • 2021-10-25 07:29:44
  • OfStack

Preface

Derivation is a way to quickly create a sequence from one or more iterators. It can combine looping with conditional judgment, thus avoiding tedious code. Derivation is typical of Python style

Python language has a unique deductive grammar, which is equivalent to the existence of grammar sugar, and can help you write more concise and cool code in some occasions. But without it, it won't have much impact. The Python language has several different types of derivation.

1. Table derivation

List derivation is a way to quickly generate lists. It takes the form of a 1-paragraph statement enclosed in square brackets, as shown in the following example:


lis = [x * x for x in range(1, 10)]
 
print(lis)

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81]

The list derivation should be understood in this way. First, the for loop is executed. For every x, it is substituted into x*x for operation, and the result is added to a new list one by one. The loop ends and the final list is obtained. It is equivalent to the following code:


lis = []
for i in range(1, 10):
    lis.append(i*i)
    
print(lis)

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81]

The list derivation provides us with a method of generating a list that implements more complex logic in one line. Its core syntax is to encapsulate the generated logic with brackets [].

List derivation has multiple uses:

Add conditional statement


lis = [x * x for x in range(1, 11) if x % 2 == 0]

Output

[4, 16, 36, 64, 100]

Multiple cycle


lis = [a + b for a in '123' for b in 'abc']

Output

['1a', '1b', '1c', '2a', '2b', '2c', '3a', '3b', '3c']

More usage


dic = {"name": "mumu", "age": "18"}
a = [k+":"+v for k, v in dic.items()]
print(a) # ['name:mumu', 'age:18']

2. Dictionary derivation


dic = {x: x**2 for x in (2, 4, 6)}
print(dic)
 
print(type(dic))

Note: x: x**2. The middle colon indicates key on the left and value on the right.

Output:

{2: 4, 4: 16, 6: 36}
< class 'dict' >

3. Set derivation


a = {x for x in 'abracadabra' if x not in 'abc'}
print(a)
 
print(type(a))

Output:

{'r', 'd'}
< class 'set' >

4. Tuple derivation?

There is no tuple derivation.


tup = (x for x in range(9))
print(tup)
print(type(tup))
<generator object <genexpr> at 0x0000013DB865AA40>
<class 'generator'>

To generate tuples in a similar way, you need to explicitly call the tuple's type conversion function tuple (), as follows:


tup = tuple(x for x in range(9))
print(tup)
print(type(tup))

Output:

(0, 1, 2, 3, 4, 5, 6, 7, 8)
< class 'tuple' >

Summarize


Related articles: