python base (16): built-in function (B)

1. lamda anonymous function

In order to address the needs of ⽽ ⼀ some simple design ⼀ sentence function
# Calculated n times n ⽅ 
DEF FUNC (n):
  return n ** n
 Print (FUNC (10 ))
 
F
= the lambda n: n ** n Print (F (10))
lambda table above shows the anonymous function, do not need to declare Using def, ⼀ words can declare a ⼀ functions.
grammar:
Function name = lambda parameter: Return value
note:
1. The parameter may have multiple functions, multiple parameters separated by commas Use
2. anonymous function no matter how complex, can only write ⼀ ⾏ and return directly after the end of the logical data
3. normal function return value and ⼀ like, can be any data type
Anonymous function is not to say ⼀ given no name, the screen for individual cases from the former variable is ⼀ a function name, he said he was anonymous because when we look through __name__ is no name, the system ⼀ called lambda, in tune Use when there is nothing special, like a normal function call Use can be.

2. sorted()

Sort function.
grammar:
sorted(Iterable, key=None, reverse=False)
  Iterable: iterables
  key: collation (sorting function), each element in the sorted ⼀ inner iteration object will be passed to this function of the parameters, make the operation of sorting the result of the function
  reverse: whether it is a flashback, True: flashbacks, False: positive sequence
= LST [1,5,3,4,6 ] 
lst2 = the sorted (LST)
 Print (LST) # original list will not change 
Print (lst2) # new returned list is sorted

DIC = {. 1: ' A ' ,. 3: ' C ' :, 2 ' B ' } Print (the sorted (DIC)) # Key If the dictionary is returned after the sort.
Using a combination of function and
# Into ⾏ sort of character string ⻓ 
LST = [ " twist vine " , " Okamoto Jiro " , " CIA " , " fox " ]
 
# Calculation of string ⻓ DEF FUNC (S):   return len (S ) Print (the sorted (LST, FUNC = Key))
Using the combination and lambda
# Into ⾏ sort of character string ⻓ 
LST = [ " twist vine " , " Okamoto Jiro " , " CIA " , " fox " ]
 
# Calculation of string ⻓ DEF FUNC (S):   return len (S )
Print (the sorted (LST, Key = the lambda S: len (S)))
LST
= [{ " ID " :. 1, " name " : ' Alex ' , " Age " : 18 is}, { " ID ":2, "name " : ' wusir ' , " Age " : 16}, { " ID " :. 3, " name " : ' Taibai ' , " Age " :. 17 }] # by age in learning ⽣ information into ⾏ sorting Print (the sorted ( LST, Key = the lambda E: E [ ' Age ' ]))

3. filter()

Filter function
grammar:
fifilter(function. Iterable)
  function: function to filter Use, in fifilter will automatically put iterable elements are passed to the function of, and is determined according to the function returns True or False if this data is retained
  Iterable: iterables
lst = [1,2,3,4,5,6,7]
ll = filter(lambda x: x%2==0, lst) # 筛选所有的偶数
print(ll)
print(list(ll))

lst
= [{"id":1, "name":'alex', "age":18}, {"id":2, "name":'wusir', "age":16}, {"id":3, "name" : ' Taibai ' , " Age " :. 17 }] FL = filter ( the lambda E: E [ ' Age ' ]> 16, LST) # screening data Age below approximately 16 Print (List (FL))

4. map()

Mapping function
grammar:
map (function, iterable) can perform while mapping iterables ⼀ each element, respectively, function to take YES
Calculation List Zhongping ⽅ each element, and returns the new list
def func(e):
  return e*e
mp = map(func, [1, 2, 3, 4, 5])
print(mp)
print(list(mp))
Rewrite lambda
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5])))
Calculating the position of the same in both lists and data
# Calculation data the same two positions, and a list 
LST1 = [. 1, 2,. 3,. 4,. 5 ] 
lst2 = [2,. 4,. 6,. 8, 10 ]
 Print (List (Map ( the lambda X, Y: X + y, lst1, lst2)))

5. Recursion

Using the present transfer function in the chest upwards function is recursive
DEF FUNC ():
   Print ( " Who am I " ) 
  FUNC () 
FUNC ()
The depth of recursion in python from the largest to 998
def foo(n):
  print(n)
  n += 1
  foo(n)
foo(1)
Recursive to apply it:
We can use the recursion to traverse a variety of tree, such as our folder system, can use the recursion to loop through all the files in the folder.
Import OS
 DEF Read (filepath, n-): 
  Files = the os.listdir (filepath) # acquired in the current folder for all files 
  for Fi in Files: # traverse folder in the file, but individual cases from the acquired this layer of file names 
    fi_d = the os.path.join (filepath, Fi) # filling with the acquired folder File folder + 
    IF os.path.isdir (fi_d): # If the file is the file at the path folder 
      Print ( " \ T " * n-, Fi) 
      Read (fi_d, n- + 1'd) # continue the same operation ⾏ 
    the else :
      Print ( " \ T " * n-, Fi) #Recursive out-connector. In individual cases from the final implicit return # recursive traversal of Contents all files 
the Read ( ' ../oldboy/ ' , 0)

6. binary search

Find ⼆ points, each can exclude data halfway, looking very ADVANCED efficiency, but the limitations of comparing zoomed, there must be
Using the motif sequences can find ⼆ points.
Requirements: must find a sequence is an ordered sequence.
# Determines whether or not n in the lst appear in. If the return to the position where n 
# ⼆ recursive binary search algorithm comes in handy --- 
lst = [22, 33, 44 , 55, 66, 77, 88, 99, 101, 238, 345, 456, 567, 678, 789 ] 
n- = 567 
left = 0 
right = len (LST) -. 1 
COUNT =. 1
 the while left <= right: 
  Middle = (left + right) // 2
  IF n-< LST [Middle] : 
    right = Middle -. 1
  elif n-> LST [Middle]: 
    left = Middle +. 1
  the else :
    Print (COUNT)
    Print (Middle)
    BREAK
  COUNT = COUNT +. 1
 the else :
  Print ( " not present " )
 
# general recursive version ⼆ division method DEF binary_search (n-, left, right):   IF left <= right:     Middle = (left + right) // 2     IF n-< LST [Middle]:       right = Middle -. 1     elif n-> LST [Middle]:       left = Middle +. 1     the else :       return Middle     return binary_search (n-, left, right) # this return must be added to or received to always None .   the else:     return -1
print(binary_search(567, 0, len(lst)-1))
# 另类⼆分法, 很难计算位置. def binary_search(ls, target):   left = 0   right = len(ls) - 1   if left > right:     print("不在这⾥")   middle = (left + right) // 2   if target < ls[middle]:     return binary_search(ls[:middle], target)   elif target > ls[middle]:     return binary_search(ls[middle+1:], target)   else:     Print ( " in individual cases from " )
binary_search (LST,
567)

Guess you like

Origin www.cnblogs.com/liuhui0308/p/11815968.html