derivational
What is a derivation
Derivative is a simplified way of using for loops to iterate over the data in an iterable object into a container. Simply put, it is a process of iterating over all the data in an iterable object with a single line of a for loop statement, and then processing the traversed data into the corresponding container.
Acting similarly to derivation is the ternary operator, which is a simplified way of using conditional judgment statements.
Grammar:
val for val in Iterable
just likeData stored in containers
+ for loop statement
Derivatives are expressed in three ways, each of which wraps the derivative statement in the corresponding symbol:
- List derivation try: [val for val in Iterable]
- Set Derivative: {val for val in Iterable}
- Dictionary derivation: {x,y for x,y in Iterable}
List Derivative:
The list is pushed into the style, and the traversed data ends up as a list data.
basic grammar
10 data are deposited in the list:
# Regular write-ups lst = [] for i in range(1, 11): (i) print(lst) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Deductive writing lst = [i for i in range(1, 11)] print(lst) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Other Uses
Single-loop derivatives:
# Process data in containers: [1, 2, 3, 4, 5] -> [3, 6, 9, 12, 15] lst = [1, 2, 3, 4, 5] # Ordinary writing new_lst = [] for i in lst: res = i * 3 new_lst.append(res) print(new_lst) # [3, 6, 9, 12, 15] # Deductive writing new_lst = [i * 3 for i in lst] print(new_lst) # [3, 6, 9, 12, 15]
One-loop derivatives with judgment conditions:
# Filter out the odd numbers lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Ordinary writing new_lst = [] for i in lst: if i % 2 == 1: new_lst.append(i) print(new_lst) # [1, 3, 5, 7, 9] # Deductive writing # Deductive use of a single branch can only be used after the end of a for statement new_lst = [i for i in lst if i % 2 == 1] print(new_lst) # [1, 3, 5, 7, 9]
Multi-cycle derivatives:
# Sum the data in two lists. lst = [1, 2, 3] lst1 = [11, 22, 33] # Ordinary methods new_lst = [] for i in lst: for j in lst1: res = i + j new_lst.append(res) print(new_lst) # [12, 23, 34, 13, 24, 35, 14, 25, 36] # Deductive writing new_lst = [i + j for i in lst for j in lst1] print(new_lst) # [12, 23, 34, 13, 24, 35, 14, 25, 36]
List Derivative Practice Problems
- 1. Turn the data in the dictionary into ['x=A', 'y=B', 'z=c'] style {'x': 'A', 'y': 'B', 'z': 'C' }
- 2. Make the elements used plain lowercase ["ADDD", "ddddd", "DDaa", "ssss"]
- 3, x is an even number between 0-5, y is an odd number between 0-5 x, y together into a tuple, put into the list of
- 4. Use list derivatives to make all the operations in the 99 multiplication table.
- 5、Find the product of matrices and elements in M,N
M = [[1,2,3], [4,5,6], [7,8,9]]
N = [[2,2,2], [3,3,3], [4,4,4]]
# One of the solutions to the fifth question # => Realization effect 1 [2, 4, 6, 12, 15, 18, 28, 32, 36] # =>Realization effect 2 [[2, 4, 6], [12, 15, 18], [28, 32, 36]] # Effects realized 1 lst_new = [] for i in range(len(M)) : for j in range(len(N)) : res = M[i][j] * N[i][j] lst_new.append(res) print(lst_new) # Deductive writing res = [M[i][j]*N[i][j] for i in range(len(M)) for j in range(len(N))] print(res) # Effects realized 2 lst_new = [] for i in range(len(M)) : lst_new2 = [] for j in range(len(N)) : res = M[i][j] * N[i][j] lst_new2.append(res) lst_new.append(lst_new2) print(lst_new) # Deductive writing res = [[M[i][j]*N[i][j] for j in range(len(M))] for i in range(len(N))] print(res)
set deduction formula
Set derivatives are used in much the same way as list derivatives, but the data obtained is a set by using curly brackets around the outside to include it.
Example question:
''' Case: Meet people aged 18 to 21 with deposits greater than or equal to 5,000 and less than or equal to 5,500 Open the card in the format of: premium VIP card old X (last name), otherwise open the card in the format of: stingy old X (last name) Tally up the types of cards opened ''' lst = [ {"name": "Liu Xinwei", "age": 18, "money": 10000}, {"name": "Liu Cong", "age": 19, "money": 5100}, {"name": "Liu Zihao", "age": 20, "money": 4800}, {"name": "Kong Xiangqun", "age": 21, "money": 2000}, {"name": "Song Yunjie.", "age": 18, "money": 20} ] # Regular write-ups setvar = set() for i in lst: if (18 <= i['age'] <= 21) and (5000 <= i['money'] <= 5500): res = 'Honored VIP Sr.' + i['name'][0] else: res = 'Stingy old man' + i['name'][0] (res) print(setvar) # {'Honored VIP Old Liu', 'Stingy Old Man Liu', 'Stingy Old Man Kong', 'Stingy Old Man Song'} # The print shows only 4 elements because of the collection's automatic de-duplication # Use set derivatives # Derivatives can only use unary branching, but can use ternary operators on return values setvar = { "VIP Card Sr." + i["name"][0] if 18 <= i["age"] <= 21 and 5000 <= i["money"] <= 5500 else "The stingy Kahlil." + i["name"][0] for i in lst} print(setvar) # {'Stingy man stuck in the old hole', 'Keying man Ka Lao Liu', 'Premium VIP Card Lao Liu', 'Keying man card Lao Song'}
dictionary derivation
Dictionary derivatives are used in the same way, but dictionary data is in the form of key-value pairs, so the data returned, or the data to be returned, has to be made into two to correspond to the key values.
Basic Grammar:
Turning a list of key-value pairs into a dictionary
lst = [{'A': 'a'}, {'B': 'b'}] dct = {k:v for i in lst for k,v in ()} print(dct) # {'A': 'a', 'B': 'b'}
Functions that dictionary derivatives are commonly used to work with
function (math.) | corresponds English -ity, -ism, -ization |
---|---|
enumerate | Enumeration that pairs the values in an iterable object one by one into tuples based on index numbers, returning iterators. |
zip | Forms a tuple of values from multiple iterable objects in one-to-one correspondence, returning an iterator. |
enumerate
Function:
Enumerations, based on the index number and the value in the Iterable, are taken one by one and paired to form a tuple, put into an iterator, and returned to the iterator.
Grammar:
enumerate(iterable, [start = 0])
Parameters:
iterable: iterable data
start: you can select the start index number (default indexing starts from 0)
Basic Syntax.
from collections import Iterator lst = ['East', 'South', 'West', 'North'] # Basic use it = enumerate(lst) # Implement function return iterator print(isinstance(it, Iterator)) # True # Strongly converted to a list new_lst = list(it) print(new_lst) # [(0, 'East'), (1, 'South'), (2, 'West'), (3, 'North')] """ You can see that the data in the meta-list inside and the corresponding index numbers correspond one by one into the tuple """
In the above example, if you use the dictionary derivation with the enumerate function, you can achieve the goal of composing a dictionary in one sentence.
from collections import Iterator lst = ['East', 'South', 'West', 'North'] # enumerate with dictionary derivatives into a dictionary dct = {k: v for k, v in enumerate(lst)} print(dct) # {0: 'East', 1: 'South', 2: 'West', 3: 'North'}
zip
Function:
Take the values from multiple Iterable, one by one, and pair them up to form a tuple into an iterator, and if an element is more than one, it will be discarded if there is no match.
Grammar:
zip(iterable, iterable1, ……)
The argument is one iterable object.
Basic Grammar:
In the following example, the elements of the three lists are formed into a tuple in one-to-one correspondence, but the smallest list has only three elements, so it can only be formed into three pairs of tuples in one-to-one correspondence, and the extra elements are discarded.
lst1 = [1, 2, 3, 4, 5] lst2 = ['a', 'b', 'c', 'd'] lst3 = ['A', 'B', 'C'] it = zip(lst1, lst2, lst3) lst = list(it) print(lst) # [(1, 'a', 'A'), (2, 'b', 'B'), (3, 'c', 'C')]
Why is there no tuple derivation?
We're done with derivatives here, but then we realize that a derivative is just using a for loop in a container, so why no tuple derivatives?
Prioritize the use of derivatives
Sometimes we need to store a large number of values in a list or some other container, how do we usually use it? For example, when initializing a list do we use a for loop and append to create it?
Here we note that, if the conditions allow, then we must be to prioritize the use of derivation rather than for loop plus append, the reason is very simple, because of the difference in the underlying logic, so that the derivation of the execution speed compared to the for loop plus append faster.
import time # Loop through the list to insert data start_time = time.perf_counter() lst = [] for i in range(15000000): (i) end_time = time.perf_counter() print(end_time - start_time) # 1.7453036000000002 """ Deductive is faster than cyclic """ start_time = time.perf_counter() new_lst1 = [i for i in range(15000000)] end_time = time.perf_counter() print(end_time - start_time) # 0.7337192000000001
After testing we can see that the derivatives are about twice as fast as the for loop, what causes this? Remember that we have previously used thedis
Module?
import dis def loop(): lst = [] for i in range(10): (i) return lst def der(): lst = [i for i in range(10)] return lst (loop) print('-' * 100) (der)
The results are as follows:
4 0 BUILD_LIST 0
2 STORE_FAST 0 (lst)
5 4 SETUP_LOOP 26 (to 32)
6 LOAD_GLOBAL 0 (range)
8 LOAD_CONST 1 (10)
10 CALL_FUNCTION 1
12 GET_ITER
>> 14 FOR_ITER 14 (to 30)
16 STORE_FAST 1 (i)
6 18 LOAD_FAST 0 (lst)
20 LOAD_ATTR 1 (append)
22 LOAD_FAST 1 (i)
24 CALL_FUNCTION 1
26 POP_TOP
28 JUMP_ABSOLUTE 14
>> 30 POP_BLOCK
7 >> 32 LOAD_FAST 0 (lst)
34 RETURN_VALUE
-----------------------------------------------------------------------------
11 0 LOAD_CONST 1 (<code object <listcomp> at 0x000002C71AD950C0, file "", line 11>)
2 LOAD_CONST 2 ('der.<locals>.<listcomp>')
4 MAKE_FUNCTION 0
6 LOAD_GLOBAL 0 (range)
8 LOAD_CONST 3 (10)
10 CALL_FUNCTION 1
12 GET_ITER
14 CALL_FUNCTION 1
16 STORE_FAST 0 (lst)
12 18 LOAD_FAST 0 (lst)
20 RETURN_VALUE
From the above results, we can just see that in this case, the for loop has a few more sessions than the derivatives because of the start of the definition of the list, the append method in the loop is used, so the speed becomes slow in comparison, and this is the reason.
Again, we'll say this again, so that when you run into doubts about speed and underpinnings and so on, you can simply use thetimeit
cap (a poem)dis
Go for verification and short answer understanding.
To this point this article on the use of Python derivatives details of the article is introduced to this, more related Python derivatives content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!