python base (16): built-in function

1. lamda anonymous function In order to solve some simple requirements_Designed_sentence function # Calculation n Of n Secondary_ def func(n): return ...
1. lamda anonymous function In order to solve some simple requirements_Designed_sentence function
# Calculation n Of n Secondary_ def func(n): return n**n print(func(10))
f = lambda n: n**n print(f(10))
The lambda table_is an anonymous function and does not require def to declare. In a sentence, you can declare functions. Grammar: Function name= lambda parameter: return value Be careful: 1. Functions can have multiple parameters, separated by commas 2. Anonymous functions, however complex, can only be written and return data directly after logic is complete 3. Return values and normal functions, which can be of any data type An anonymous function does not mean that there must be no name. The variable before this is a function name. It says that he is anonymous because we look through u name_ without a name. All of them are called lambda. There is nothing special about it, just like the normal function tone. 2. sorted() Sort function. Grammar:
sorted(Iterable, key=None, reverse=False) Iterable: Iterable Objects key: Collation(Sort function),stay sorted Each element in an iterative object is passed internally to the function's parameters, sorted according to the result of the function operation reverse: Is it a rewind? True: Flashback, False: positive sequence
lst = [1,5,3,4,6] lst2 = sorted(lst) print(lst) # The original list will not change print(lst2) # The new list returned is sorted
dic = print(sorted(dic)) # If it is a dictionary. Then return the sorted key
Combining and functions makes_
# Sort by string degree lst = ["Spatholobus sinensis", "Okazuro", "CIA", "Fairy fox"]
# Calculate string degree def func(s): return len(s) print(sorted(lst, key=func))
Combining with lambda makes_
# Sort by string degree lst = ["Spatholobus sinensis", "Okazuro", "CIA", "Fairy fox"]
# Calculate string degree def func(s): return len(s)
print(sorted(lst, key=lambda s: len(s)))
lst = [{"id":1, "name":'alex', "age":18}, {"id":2, "name":'wusir', "age":16}, {"id":3, "name":'taibai', "age":17}] # Sort school information by age print(sorted(lst, key=lambda e: e['age']))
3. filter() Filter function Grammar:
fifilter(function. Iterable) function: _to filter the function, in the fifilter Central Club Moving Handle iterable Elements in passed to function,Then according to function Returned True perhaps False To determine whether to keep this data Iterable: Iterable Objects
lst = [1,2,3,4,5,6,7] ll = filter(lambda x: x%2==0, lst) # Filter all even numbers 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(lambda e: e['age'] > 16, lst) # Screening data for age 16 print(list(fl))
4. map() Mapping function Grammar: map(function, iterable) maps each element of an Iterable object and receives function separately Calculates the square of each element in the list, returning to the new list
def func(e): return e*e mp = map(func, [1, 2, 3, 4, 5]) print(mp) print(list(mp))
Rewrite to lambda
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5])))
Calculates the sum of data in the same location in two lists
# Calculates the sum of data in the same location in two lists lst1 = [1, 2, 3, 4, 5] lst2 = [2, 4, 6, 8, 10] print(list(map(lambda x, y: x+y, lst1, lst2)))
5. Recursion In a function, tuning the function itself is recursive.
def func(): print("Who am I?") func() func()
Recursion is deepest in python to 998
def foo(n): print(n) n += 1 foo(n) foo(1)
Recursive response: We can make_recursively traverse a variety of tree structures, such as our folder system, and make_recursively traverse all the pieces in that folder.
import os def read(filepath, n): files = os.listdir(filepath) # Get all the pieces in the current folder for fi in files: # Traverse through the pieces in the folder, This_only gets the name of the layer fi_d = os.path.join(filepath,fi) # Add Mushroom Folder to Get Mushroom Folder+Mushroom if os.path.isdir(fi_d): # If the pieces in this path are folders print("\t"*n, fi) read(fi_d, n+1) # Continue with the same operation else: print("\t"*n, fi) # Recursive outflow. Ultimately implied here return
#Recursive Traversal Record All read('../oldboy/', 0)
6. Binary Search Searching separately, which excludes half of the data at a time, is very efficient, but the limitations are comparable. There must be Sequence sequences can be used to separate and locate. Requirement: The sequence to be found must be ordered.
# judge n Is it lst Appears in. Return if it appears n Location # Find each other---Recursive algorithm 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 while left <= right: middle = (left + right) // 2 if n < lst[middle]: right = middle - 1 elif n > lst[middle]: left = middle + 1 else: print(count) print(middle) break count = count + 1 else: print("Non-existent")
# Common Recursive Version Fractionation 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 else: return middle return binary_search(n, left, right) # this return Must be added. Otherwise receiveTo always be None. else: return -1
print(binary_search(567, 0, len(lst)-1))
# Alternative Division, It is difficult to calculate location. def binary_search(ls, target): left = 0 right = len(ls) - 1 if left > right: print("Not here") 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("Here_")
binary_search(lst, 567)

7 November 2019, 12:22 | Views: 6650

Add new comment

For adding a comment, please log in
or create account

0 comments