Python Foundation day 11th-complement of built-in functions, built-in functions with lambda, recursive

Source: Internet
Author: User
Tags generator macbook

First, supplements1, the generator expression in the form of multiple functions in collaboration between the work.

Example: Make a bun to eat a bun

Advantage: save more memory.

The principle of the above example: key ★★★★★

Source:

Import Timeimport random# decorator def init (func):    initialization of the generator expression '    def wrapper (*args,**kwargs):        G=func (*args , **kwargs)        next (g)        return G    return wrapperdef Cook (people,count): '    define a chef ' for    I in range ( count):        time.sleep (Random.randrange (1,4))        x= ' bun%s '% i        print (' \033[47m Cook Buns:%s\033[0m '%x)        People.send (x) @initdef Eater (name):    ' Define a foodie ' while    True:        bun=yield        Time.sleep ( Random.randrange (1, 4))        print (' \033[46m%s start eating%s\033[0m '% (Name,bun)) Cook (Eater (' Little White '), 20)

2, three-dimensional expression of the generator expression complement.

Cases:

Requirements: The sum of the prices of all items in a product document

There is a. txt file that contains the contents of the product as follows:

The code is as follows:

The above code is too long, here with the ternary expression in the list parsing to streamline the code, but the list parsing is to put the contents of the file into memory space, will cause excessive memory consumption. Therefore, it is best to use the generator expression, one to simplify the code, and secondly, save memory.

The code is as follows:

Money = []with open (' shop_list ', ' R ', encoding= ' utf-8 ') as f:    t = (float (line.split (' | ') [1]) * INT (line.split (' | ') [2]) for line in F)    print (sum (t))

Output Result:

724280.0

3, the Simulation database query operation

Requirements: The 2nd point in the example of the data out, stitching into a structure of the same data, similar to the query function of the database

Analysis: So the data is isolated, they are just a string of strings, and then splicing these strings into a dictionary form, so that we can find the corresponding value by the key.

The list of items is as follows:

The code is as follows:

Goods_info = []         # is used to store all goods, each item is stored in the form of a dictionary with open (' Shop_list ', ' R ', encoding= ' utf-8 ') as f:    goods_info = [{' Name ': Line.split (' | ') [0], ' Price ': line.split (' | ') [1], ' count ': Line.split (' | ') [2]} for line in F]print (Goods_info)

Output Result:

[{'name':'Apple',' Price':'3.2','Count':' +'}, {'name':'Banana',' Price':'1.8','Count':' -'}, {'name':'ipad',' Price':'4000','Count':' -'}, {'name':'MacBook Pro',' Price':'10000','Count':' -'}, {'name':'Soap',' Price':'2','Count':'10000'}]
View Code

Change required: Only items with a price greater than or equal to 4000 are taken.

The code is as follows:

Goods_info = []         # is used to store all goods, each item is stored in the form of a dictionary with open (' Shop_list ', ' R ', encoding= ' utf-8 ') as f:    goods_info = [{' Name ': Line.split (' | ') [0], ' Price ': Float (line.split (' | ') [1]), ' count ': Int (line.split (' | ') [2])} for line in F                   if float (line.split (' | ') [1]) >= 4000]print (Goods_info)

Output Result:

 [{ " name   ' :  '  ipad   ' ,  '  price   ' : 4000.0,  '  count  : +}, {"  name  Span style= "COLOR: #800000" > ' :  " macbook Pro   ", "   Price   ": 10000.0, "  count  " : ()] 
View Code

second, built-in functions and lambda

Previously learned functions are the function name, the function name is used to bind the value, and the definition of the variable name, when creating a function, when the function name is bound to a value, the value of the reference counter is added 1, once there is no function name to reference this value, this value will be the Python memory recycling mechanism to be recycled. But anonymous functions are excluded.

1. anonymous function--lambda(1) Features:

(1) No Name of the letter

(2) The naming rules for function parameters are the same as those for known functions.

(3) directly write parameter names without parentheses when defining formal parameters

(4) A line of code to complete the creation of functions

(5) Comes with return effect, so there must be a return value

(6) The Python memory recycling mechanism will be recycled after the definition is complete.

(2) format:

  The parameters of the lambda function: the function body of the function body # Anonymous function is equivalent to the Retturn return value of the famous function.

(3) Application scenario:

Sometimes we only need to use the function once, and we do not want to clean up the famous function when we can use this anonymous function.

(4) Example:

Python Foundation day 11th-complement of built-in functions, built-in functions with lambda, recursive

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.