Python built-in functions 2

Source: Internet
Author: User
Tags iterable

I. Lambda anonymous function

In order to solve the simple needs of the design of the sentence function, some functions need to use function function, but not complex, in order to avoid the difficulty of the function name awkward, will use the anonymous function.

Lambda table? is an anonymous function. You don't need a def to declare it, a sentence can be declared? functions

Syntax: function name = lambda parameter: return value

# n to calculate n times? def func (N):     return n**nprint(func (Lambda n:n**nprint(f ( 10))

Attention:
1. The parameters of a function can have more than one. Between multiple parameters? Comma separated
2. Anonymous functions no matter how complex. can only write??, and return data directly after the logic ends
3. Return value and normal function, can be any data type

Two. Sorted ()

Syntax: Sorted (iterable, Key=none, Reverse=false)

Iterable: An Iterative object

Key: The collation (sort function), within the sorted, will iterate over each element in the object to the parameters of the function. Sort by the result of a function operation

Reverse: Whether it is a flashback. True: Flashback, False: Positive sequence

LST = [1,5,3,4,6= sorted (LST)print#  original list does not change print# The new list returned is a sorted dic = {1:'A', 3:'C', 2:'  B'}print#  If it is a dictionary. Returns the key after the sort

The weight of the key sort is essentially the size of the number, so the key parameter is also the number

# according to the string? sort lst = [" Twist Vine "" Gamben  " " CIA  "" Fox "]#  calculate string? degree def func (s):     return Len (s) Print (Sorted (LST, Key=func))

And the lambda combination?

#Sort by string?LST = ["Twist Rattan","Gamben","CIA","Fox"]#calculate a string? Degreesdeffunc (s):returnLen (s)Print(Sorted (LST, key=LambdaS:len (s))) LST= [{"ID": 1,"name":'Alex'," Age": 18},       {"ID": 2,"name":'Wusir'," Age": 16},       {"ID": 3,"name":'Taibai'," Age": 17}]#according to the age of learning? Sort information inPrint(Sorted (LST, key=Lambdae:e[' Age']))

Three. Filter ()

Syntax: Filter (function. iterable)

Function:? To filter the functions. In the filter, the elements in the iterable are transferred to the function. It then determines whether the data is persisted based on the true or false returned by the function.

Iterable: An Iterative object

LST = [1,2,3,4,5,6,7]ll= Filter (LambdaX:x%2==0, LST)#Filter all the even numbersPrint(LL)Print(LL) LST= [{"ID": 1,"name":'Alex'," Age": 18},       {"ID": 2,"name":'Wusir'," Age": 16},       {"ID": 3,"name":'Taibai'," Age": 17}]FL= Filter (Lambdae:e[' Age'] >, LST)#filter age? data for 16Print(List (fl))

Four. Map ()

Syntax: Map (function, iterable) can map every element in an iterative object. Take the function separately.

Calculates the flat of each element in the list? , return to the new list

def func (E):     return e*= Map (func, [1, 2, 3, 4, 5])print(MP)print

Write with Lambda

Print (List (map (lambda x:x * x, [1, 2, 3, 4, 5])))

Calculates the data of the same position in the two list and

# calculates the lst1 of the data for the same position in two lists = [1, 2, 3, 4, 5 = [2, 4, 6, 8,]print(list (map (Lambda X, y:x+

Five. Recursion

In the function of the function of the book? is recursion.

def func ():     Print (" who I am ")    func () func ()

The depth of recursion in Python is the most? to 998, with import sys you can change

def foo (n):     Print (n)     + = 1    foo (n) foo (1)

Recursive should be?: We can make the recursive return traversal of various tree structures, such as our clip system. You can make the recursive return traverse all the parts in the folder.

ImportOSdefRead (filepath, n): Files= Os.listdir (filepath)#get all the parts in the current folder     forFiinchFiles#traverse the pieces in the folder, this is the only one that gets the name of the layer?Fi_d = Os.path.join (FILEPATH,FI)#plus?? Folder to get the folder + parts        ifOs.path.isdir (fi_d):#if the part under this path is a folder             Print("\ t"*N, FI) read (Fi_d, n+1)#continue into the same operation     Else:         Print("\ t"*n, FI)#recursion out? In the end here? implies return#recursive traversal? Record all the piecesRead'.. /oldboy/', 0)

If the return value in the recursive function cannot be returned directly from the last layer, only the previous layer will be returned at each loop

Six. Sub-search

The search for points. You can exclude half of the data at a time. How efficient is the search? But the limitations of comparison? Must be ordered sequence to be able to make?? Sub-search

Requirement: The lookup sequence must be an ordered sequence.

#determine if n is present in LST. If it appears, return n where#Split lookup---? recursive algorithmLST = [22, 33, 44, 55, 66, 77, 88, 99, 101, 238, 345, 456, 567,678,789]n= 567 Left=0right= Len (LST)-1Count= 1 whileLeft <=Right:middle= (left + right)//2ifN <Lst[middle]: Right= Middle-1elifn >Lst[middle]: Left= middle + 1Else:        Print(count)Print(middle) BreakCount= Count + 1Else: Print("does not exist")#General recursive version of the methoddefBinary_search (n, left, right):ifLeft <=Right:middle= (left+right)//2ifN <Lst[middle]: Right= Middle-1elifn >Lst[middle]: l EFT= middle + 1Else:             returnMiddlereturnBinary_search (n, left, right)#This return must be added. Otherwise receiveto the Forever is none. Else:         return-1Print(Binary_search (567, 0, Len (LST)-1))#It is difficult to calculate the position by alternative method.defbinary_search (LS, target): left=0 Right= Len (ls)-1ifLeft >Right :Print("It's not here?") Middle= (left + right)//2ifTarget <Ls[middle]:returnBinary_search (Ls[:middle], target)elifTarget >Ls[middle]:returnBinary_search (ls[middle+1:], target)Else:             Print("in this?") Binary_search (LST,567)


Python built-in functions 2

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.