day13 built in functions and Derivations
Summary:
- Anonymous function
- generator
- Built in function
- Additional "derivation, which belongs to the knowledge of data type, and the internal high-level usage involves [generator] and [function]"
1. Anonymous function
Traditional functions (well-known functions)
def fuc(): print("This is a famous function")
Anonymous functions are defined based on the lambda keyword: lambda parameter: function body
-
Parameter. Any parameter is supported
lambda x: Function body lambda x1,x2: Function body lambda *args, **kwargs: Function body
-
Function body, only single line code is supported
def xxx(x): return x + 100 lambda x: x + 100
-
Return value. By default, the result of single line code execution in the function body is returned to the executor of the function
func = lambda x: x + 100 v1 = func(10) print(v1) # 110
Anonymous functions are suitable for simple business processing and can create functions quickly and simply.
Extensions: ternary operations
establish if condition else Not established
Simple functions use the anonymous function lambda
Simple conditional statements use ternary operations ()
2. Generator
The generator function is written with the keyword function + yield. In specific cases, working together can help us save memory. (if the generator object is not executed once, the memory space will be reallocated once, and the modified space will be destroyed after execution)
- Add a yield inside the function
def fun(): print(123) yield 789 # The object can be any data type q = fun() # When calling the generator for a function, the internal code of the function will not be executed. By default, a generator object is returned, which is very useful next("Generator object") # Method of executing generator internal functions
def fun(): print(1) yield 2 # Meet yield print(3) yield 4 # The object is returned to the caller q = fun() # When calling the generator for a function, the internal code of the function will not be executed. By default, a generator object is returned, which is very useful print(next(q)) # Method of executing generator internal functions print(next(q)) >>> 1 2 3 4
When using next to execute the generator, if it encounters yield, it will return the object and temporarily store the number of execution lines. The next time it uses next to execute the function, it will continue to execute. If it encounters the return keyword during the execution of the generator object, it will report an error (indicating that the generator code has been executed): StopIteration
# In general development, the execution of generator objects is invoked by loops. # When a generator object is executed in a loop, an error will not be reported because of return dafa = fun() for item in data: next(item) print(item)
Application scenario of generator
Save memory overhead
Here comes the mold
-
Generate 300w random 4-digit numbers and print them
-
Direct loop (memory intensive and quite large)
-
Dynamic creation, using one to create one
-
-
import random val = random.randint(1000, 9999) print(val)
import random data_list = [] for i in range(300000000): val = random.randint(1000, 9999) data_list.append(val) # When reusing, remove the data_list. # ...
import random def gen_random_num(max_count): counter = 0 while counter < max_count: yield random.randint(1000, 9999) counter += 1 data_list = gen_random_num(3000000) # When reusing, remove the data_list.
- Suppose you are asked to obtain 300w pieces of data from a data source (you can learn to operate MySQL or Redis and other data sources later to understand the idea).
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-WL0r2vks-1625702068372)(assets/image-20210707081845043.png)]
Therefore, when we need to create a lot of data in memory in the future, we can think of using generator based to realize bit by bit generation (bit by bit production) to save memory overhead.
extend
# Another execution of the generator is data send(None) def func(): print(111) v1 = yield 1 print(v1) print(222) v2 = yield 2 print(v2) print(333) v3 = yield 3 print(v3) print(444) data = func() n1 = data.send(None)# v1 = None assigns null to the object that accepts yield print(n1) n2 = data.send(666) print(n2) n3 = data.send(777) print(n3) n4 = data.send(888) print(n4)
3. Built in function
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-1OJveREg-1625702068373)(assets/image-20210707142345764.png)]
list
-
Group 1 (7 mathematical operation Series)
- abs() # absolute value - pow() # The third power of index pow(2,3) 2 - sum() # Summation passes in an iteratable type - merchant,remainder = dicmod(Divisor) # Quotient and remainder - round(Decimal, number of rounded digits) # Keep a few decimal places and round them
-
Group 2 (comparison)
- min # Min (iteration object, key = comparison rule) - max # Max min (iteration object, key = comparison rule) - all # Are all Trun - any # Is there a Trun
-
Group 3 (binary conversion)
- bin # Ten - > two - oct # Ten - > eight - hex # Ten - > sixteen
-
The fourth group (get the Unicode code point corresponding to the character (decimal))
- ord # str -> Unicode - chr # Unicode -> str
-
Group 5 (type conversion)
- int - float - str - bytes # Compressed to utf-8\gbk encoding eg: turn utf-8 - v1 = "Yang Guofei" - v2 = v1.encode("utf-8") # bytes type - v3 = betes(v1,encoding="utf-8") # bytes type - bool - list - dict - tuple - set
-
Group 6 (mystery group)
- len - print - open - type - range - enumerate # Loop through the list data and maintain a numeric increment for num, value in enumerate(starting point, list): print(num,value) - id - hash # Returns the hash value of the object v1 = hash("h") - help # Generally, you want to check the prompt of function temporarily at the terminal - zip # Zipper, you know, the return is (iteratable type) 'zip' element is the ancestor - callable # Judge whether the object can be executed - sorted # sort - sorted("Iteratable type",key="Sorting rules are generally passed to a function",reverse=True)
sorted eg
data_list = [ '1-5 Compilers and Interpreters .mp4', '1-17 Homework today.mp4', '1-9 Python Interpreter type.mp4', '1-16 Today's summary.mp4', '1-2 Creation of classroom notes.mp4', '1-15 Pycharm Use and crack( win System).mp4', '1-12 python Installation of interpreter( mac System).mp4', '1-13 python Installation of interpreter( win System).mp4', '1-8 Python introduce.mp4', '1-7 Classification of programming languages.mp4', '1-3 Common computer basic concepts.mp4', '1-14 Pycharm Use and crack( mac System).mp4', '1-10 CPython Interpreter version.mp4', '1-1 Today's summary.mp4', '1-6 Three essential things about learning programming.mp4', '1-18 Homework answers and explanations.mp4', '1-4 programing language.mp4', '1-11 Description of environment construction.mp4' ] result = sorted(data_list, key=lambda x: int(x.split(' ')[0].split("-")[-1]) ) print(result)
4 derivation
Derivation is a very convenient function provided in Python, which allows us to initialize some values while creating list, dict, tuple and set through one line of code.
Please create a list and initialize: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9... 299 integer elements in the list.
data = [] for i in range(300): data.append(i) [Pass in variable name for i in range(boundary) if You can add a judgment statement to store the object when it is established ]
-
list
num_list = [ i for i in range(10)] num_list = [ [i,i] for i in range(10)] num_list = [ [i,i] for i in range(10) if i > 6 ]
-
aggregate
num_set = { i for i in range(10)} num_set = { (i,i,i) for i in range(10)} num_set = { (i,i,i) for i in range(10) if i>3}
-
Dictionaries
num_dict = { i:i for i in range(10)} num_dict = { i:(i,11) for i in range(10)} num_dict = { i:(i,11) for i in range(10) if i>7}
-
Tuples, different from other types.
# Instead of immediately executing an internal loop to generate data, you get a generator. data = (i for i in range(10)) print(data) for item in data: print(item)
Exercises
-
Removes the of each element in the list mp4 suffix.
data_list = [ '1-5 Compilers and Interpreters .mp4', '1-17 Homework today.mp4', '1-9 Python Interpreter type.mp4', '1-16 Today's summary.mp4', '1-2 Creation of classroom notes.mp4', '1-15 Pycharm Use and crack( win System).mp4', '1-12 python Installation of interpreter( mac System).mp4', '1-13 python Installation of interpreter( win System).mp4', '1-8 Python introduce.mp4', '1-7 Classification of programming languages.mp4', '1-3 Common computer basic concepts.mp4', '1-14 Pycharm Use and crack( mac System).mp4', '1-10 CPython Interpreter version.mp4', '1-1 Today's summary.mp4', '1-6 Three essential things about learning programming.mp4', '1-18 Homework answers and explanations.mp4', '1-4 programing language.mp4', '1-11 Description of environment construction.mp4' ] result = [] for item in data_list: result.append(item.rsplit('.',1)[0]) result = [ item.rsplit('.',1)[0] for item in data_list]
-
Format the elements in the dictionary according to the key value and use them finally; Connect.
info = { "name":"Wu Peiqi", "email":"xxx@live.com", "gender":"male", } data_list [] for k,v in info.items(): temp = "{}-{}".format(k,v) temp.append(data_list) resutl = ";".join(data) result = ";".join( [ "{}-{}".format(k,v) for k,v in info.items()] )
-
Sort the dictionaries from small to large according to the key, and then splice them according to the following format. (internal processing requirements of wechat payment API)
info = { 'sign_type': "MD5", 'out_refund_no': "12323", 'appid': 'wx55cca0b94f723dc7', 'mch_id': '1526049051', 'out_trade_no': "ffff", 'nonce_str': "sdfdffd", 'total_fee': 9901, 'refund_fee': 10000 } data = "&".join(["{}={}".format(key, value) for key, value in sorted(info.items(), key=lambda x: x[0])]) print(data)
-
Look at the code writing results
def func(): print(123) data_list = [func for i in range(10)] print(data_list) # This only holds the function name
-
Look at the code writing results
def func(num): return num + 100 data_list = [func(i) for i in range(10)] print(data_list)
-
Look at the code writing results (execution errors, through which you can better understand the execution process)
def func(x): return x + i data_list = [func for i in range(10)] val = data_list[0](100) print(val)
-
Look at the code writing results (Sina Weibo interview questions)
data_list = [lambda x: x + i for i in range(10)] # [function, function, function] i=9 v1 = data_list[0](100) v2 = data_list[3](100) print(v1, v2) # 109 109
Small senior
-
Derivation supports nesting
data = [ i for i in range(10)]
data = [ (i,j) for j in range(5) for i in range(10)] data = [] for i in range(10): for j in range(5): data.append( (i,j) ) data = [ [i, j] for j in range(5) for i in range(10)]
# A deck of playing cards poker_list = [ (color,num) for num in range(1,14) for color in ["heart", "spade", "Square slice", "Plum blossom"]] poker_list = [ [color, num] for num in range(1, 14) for color in ["heart", "spade", "Square slice", "Plum blossom"]] print(poker_list)
-
Brain burning interview questions
def num(): return [lambda x: i * x for i in range(4)] # 1. num() and get the return value [function, function, function] i=3 # 2. Return value of for loop # 3. Each element of the return value (2) result = [m(2) for m in num()] # [6,6,6,6] print(result)
def num(): return (lambda x: i * x for i in range(4)) # 1. num() and get the return value generator object # 2. Return value of for loop # 3. Each element of the return value (2) result = [m(2) for m in num()] # [0,2,4,6 ] print(result)
summary
- Anonymous function, create a function per line based on lambda expression. It is generally used to write simple functions.
- Ternary operation, with a line of code to deal with simple condition judgment and assignment.
- Generator, if the yield keyword in the function
- generator function
- Generator object
- Execute the code in the generator function
- next
- for (common)
- send
- Built in functions (36)
- Derivation
- General operation
- Small advanced operations
task
-
Look at the code writing results
v = [ lambda :x for x in range(10)] print(v) # The function address is a list of elements print(v[0]) # Function address print(v[0]()) # 9
-
Look at the code writing results
v = [i for i in range(10,0,-1) if i > 5] print(v) # [10,9,8,7,6]
-
Look at the code writing results
data = [lambda x:x*i for i in range(10)] print(data) # # The function address is a list of elements print(data[0](2))# 2*9 print(data[0](2) == data[8](2)) # Trun
-
Please use the list derivation to kick out the string in the list and finally generate a new list to save.
data_list = [11,22,33,"alex",455,'eirc'] new_data_list = [len(i) if type(i) == str else i for i in data_list] # Tip: you can use type to judge the type
-
Please use list derivation to implement data_ Each element in the list is judged. If it is a string type, the calculated length is placed as an element in the element of the new list; If it is an integer, put its value + 100 as an element in the element of the new list.
# If it is a string type, the calculated length is placed as an element in the element of the new list; # If it is an integer, put its value + 100 as an element in the element of the new list. data_list = [11, 22, 33, "alex", 455, 'eirc'] new_data_list = [len(i) if type(i) == str else i + 100 for i in data_list] # Please supplement the code implementation in []. print(new_data_list) # Tip: it can be implemented based on ternary operation
-
Please use dictionary derivation to construct the list into a dictionary of the specified format
data_list = [ (1,'alex',19), (2,'Old man',84), (3,'Old woman',73) ] data_dict = {k: v for k, v in enumerate(data_list, 1)}# Please use derivation to convert data_ The list constructor generates the following format: """ info_dict = { 1:(1,'alex',19), 2:(2,'Old man',84), 3:(3,'Old woman',73) } """
-
There are 4 people playing poker. Please compare the size of each person's card in the dictionary and enter the name of the winner (the victory with large value does not need to consider A).
player = { "Wu Peiqi":["heart",10], "alex":["heart",8], 'eric':["spade",3], 'killy':["Plum blossom",12], } print(max(player.items(),key=lambda item:item[-1][-1]))
-
List as many built-in functions as you can remember? [write as much as you can remember. It's not mandatory to memorize. You can write as much as you can here. If you use more public follow-up, you will naturally remember it]
min max Those binary conversions are type conversions help
-
Please write a generator function to generate the values of n Fibonacci sequences.
-
What is the Fibonacci sequence?
The result of adding the first two numbers is the next number. 1 1 2 3 5 8 13 21 34 55 ...
-
Code structure example, please supplement the code implementation on this basis.
# Mold def fib(max_count): first = 1 second = 0 count = 0 while count < max_count: next_value = first + second first = second second = next_value yield naxt_value count def fib(max_count): n1 = 1 n2 = 1 n3 = 2 for i in range(max_count): if i < 3: yield eval(f"n{i+1}") else: n1, n2, n3 = n2, n3, n2 + n3 yield n3 count = input("Please enter the number of Fibonacci series to be generated:") count = int(count) fib_generator = fib(count) for num in fib_generator: print(num)
-
0
while count < max_count:
next_value = first + second
first = second
second = next_value
yield naxt_value
count
def fib(max_count):
n1 = 1
n2 = 1
n3 = 2
for i in range(max_count):
if i < 3:
yield eval(f"n{i+1}")
else:
n1, n2, n3 = n2, n3, n2 + n3
yield n3
count = input("Please enter the number of Fibonacci series to be generated:") count = int(count) fib_generator = fib(count) for num in fib_generator: print(num) ```