Detailed Explanation of Simple and Elegant Derivation Examples in python Programming

  • 2021-12-11 18:37:29
  • OfStack

Directory 1. List derivation adds conditional statement multiple loops and more usage 2. Dictionary derivation 3. Set derivation 4. Tuple derivation

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]

To understand the list derivation, first execute the for loop, and for every x, substitute it x*x Add the result to a new list one by one, and the loop ends to get the final list. 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 colon in the middle 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))

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

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


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

Output:


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

The above is the python programming concise and elegant derivation example details, more about python programming derivation information please pay attention to other related articles on this site!


Related articles: