Python anonymous function / sort function / filter function / mapping function / Recursive / dichotomy

This article describes the Python anonymous function / sort function / filter function / mapping function / recursive / dichotomy, this paper examples of code to tell you in great detail, has a certain value for references, a friend in need can refer to
a. lamda anonymous function
  in order to solve some simple needs and design function of a word

# 计算n的n次方
def func(n):
 return n**n
print(func(10))
f = lambda n: n**n
print(f(10))

lambda represents the anonymous function. def do not need to declare, in a word can declare a function

Syntax:
    function name = lambda parameters: return value

note:

1. The parameters of the function can be separated by commas plurality of multiple parameter
  2. anonymous no matter how complex function can only write a line, and returns the data directly after the end of the logical
  3. Return value and normal functions, may any data type

Anonymous function is not to say some no name. In front of the variable here is a function name. The reason is that he was anonymous when we look through __name__ no name. Unification called lambda. There's nothing special about the time of the call place. like normal function call

Two sorted () sort function.
  Syntax: sorted (Iterable, key = None , reverse = False)

Iterable: iterables

key: collation (sorting function), each element in the interior will be sorted iteration object parameters passed to the function to sort function of the result of calculation.

reverse: whether it is a flashback True:. flashback, False: positive sequence

lst = [1,5,3,4,6]
lst2 = sorted(lst)
print(lst) # 原列表不会改变
print(lst2) # 返回的新列表是经过排序的
dic = {1:'A', 3:'C', 2:'B'}
print(sorted(dic)) # 如果是字典. 则返回排序过后的key

And functions used in combination

# 根据字符串长度进行排序
lst = ["鲁班七号", "程咬金", "安琪拉", "阿珂"]
# 计算字符串长度
def func(s):
 return len(s)
print(sorted(lst, key=func))

And lambda in combination

# 根据字符串长度进行排序
lst = ["鲁班七号", "程咬金", "安琪拉", "阿珂"]
# 计算字符串长度
def func(s):
 return len(s)
print(sorted(lst, key=lambda s: len(s)))
lst = [{"id":1, "name":'鲁班', "age":28},
  {"id":2, "name":'安琪拉', "age":16},
  {"id":3, "name":'阿珂', "age":25}]
# 按照年龄对信息进行排序
print(sorted(lst, key=lambda e: e['age']))

Three. Filter () function screening

Syntax: filter (. Function Iterable)

function: function for screening will automatically pass to the iterable the elements in the filter function is determined according to function and then return True or False if this data is retained.

  1. map () function mapping

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":'鲁班', "age":18},
  {"id":2, "name":'安琪拉', "age":16},
  {"id":3, "name":'阿珂', "age":17}]
fl = filter(lambda e: e['age'] > 16, lst) # 筛选年龄大于16的数据
print(list(fl))

Four. Map () function mapping

Syntax: map (function, iterable) can be mapped iterables each element taken separately executed function.

Calculate the square of each element of the list, returns a 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

# 计算两个列表相同位置的数据的和
lst1 = [1, 2, 3, 4, 5]
lst2 = [2, 4, 6, 8, 10]
print(list(map(lambda x, y: x+y, lst1, lst2)))

V. recursive

Call a function in the function itself is recursive

  def func():
 print("我是递归")
 func()
func()

Recursion in python depth of up to 998

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

Applied recursively:
  we can use recursion to traverse a variety of tree, such as our folder system can use recursion to loop through all the files in that folder.

import os
def func(filepath,n):
 files = os.listdir(filepath) # 查案当前文件的目录
 for file in files: # 获取每一个文件名
  # 获取文件路径
  file_p = os.path.join(filepath,file)
  if os.path.isdir(file_p): # 判断file是否是一个文件夹
   print("\t"*n,file)
   func(file_p,n+1)
  else:
   print("\t"*n,file)
func("/Volumes/扩展盘/网站css",0)

VI. Binary search

Binary search. Each half of the data can be excluded. Search efficiency is very high. But the limitations of relatively large must be ordered sequence before you can use binary search

Requirements: must find a sequence is an ordered sequence.

  # 判断n是否在lst中出现. 如果出现请返回n所在的位置
lst = [22, 33, 44, 55, 66, 77, 88, 99, 101, 238, 345, 456, 567, 678, 789]
# 非递归算法
# 使用二分法可以提高效率 前提条件有序序列
n = 88
left = 0
right = len(lst) - 1
 
while left <= right: # 边界,当右边比左边还小的时候退出循环
 mid = (left + right) // 2 # 这里必须是整除,应为索引没有小数
 if lst[mid] > n:
  right = mid - 1
 if lst[mid] < n:
  left = mid + 1
 if lst[mid] == n:
  print("找到这个数")
  break
else:
 print("没有这个数!")
# 递归来完成二分法
lst = [22, 33, 44, 55, 66, 77, 88, 99, 101, 238, 345, 456, 567, 678, 789]
def func(n,left,right):
 if left <= right:
  mid = (left + right) // 2
  if n > lst[mid]:
   left = mid + 1
   return func(n,left,right) # 递归,递归入口
  elif n < lst[mid]:
   right = mid - 1
   # 深坑,函数的返回值返回给调用者
   return func(n,left,right) # 递归
  elif lst[mid] == n:
   # print("找到了")
   return mid
 else:
  print("没找到")
  return -1 # 避免返回None
 
# 找66,左边界0,右边界len(lst) - 1
ret = func(66,0,len(lst) - 1)
print(ret)
# 递归二分法另一种形式,但是无法实现位置计算
lst = [22, 33, 44, 55, 66, 77, 88, 99, 101, 238, 345, 456, 567, 678, 789]
def func(lst,target):
 left = 0
 right = len(lst) - 1
 if left > right:
  print("没有这个数")
 middle = (left + right)//2
 if target < lst[middle]:
  return func(lst[:middle],target)
 elif target > lst[middle]:
  return func(lst[middle + 1:],target)
 elif target == lst[middle]:
  print("找到这个数了")
func(lst,101)

Core: break off both ends take the middle one cut in half.
  Two algorithms: conventional cycles, recursion

# 时间复杂度最低, 空间复杂度最低
lst1 = [5,6,7,8]
 lst2 = [0,0,0,0,0,1,1,1,1]
 for el in lst1:
 lst2[el] = 1
 lst2[4] == 1 # o(1)

I write to you, for everyone to recommend a very wide python learning resource gathering, click to enter , there is a senior programmer before learning to share experiences, study notes, there is a chance of business experience, and for everyone to carefully organize a python zero basic information to project combat, day to you on the latest technology python, prospects, learning to leave a message of small details
summarized
above is a small series to introduce Python anonymous function / sort function / filter function / mapping function / recursive / dichotomy, I want to help

Published 24 original articles · won praise 38 · views 20000 +

Guess you like

Origin blog.csdn.net/haoxun10/article/details/104761625