Anonymous functions, iterators, exception handling

Anonymous function

What is an anonymous function?

  • Function without name

Syntax format

  • lambda parameter: return value
    Anonymous functions are generally not used alone, but are often used together with other functions
res = lambda x: x ** 2

Built in function

# mapping
 format	Format: map(function,iterable) # Iteratable: iteratable object
	The first parameter is the function name, and the second parameter is the iteratable object
 process	Loop through each element in the iteratable object and pass it to function Function to save return value and return a new iteratable object with theout modifying principle.
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# def index(n):
# 	return n ** 2
print(list(map(lambda x: x ** 2, l)))

# 2. Zip (zipper)
format	filter(function , iterable)
	function Is the function name, iterable Is an iteratable object
l = [11, 22, 33]
name_list = ['jason', 'kevin', 'tony', 'jerry']
# The elements in the two lists correspond one to one in the form of small tuples and are placed in a new list
new_list = []
for i in range(len(l)):
res = list(zip(l, name_list))

# 3.max and min max are the maximum and min is the minimum
 format	max(*args, key=None)
	min(*args, key=None)
	parameter key It is used to specify a function. The function of this function is to formulate sorting rules. It is generally used lambda function
d = {
# Compare values and return key
def index(key):
	return d[key]
print(max(d,key=lambda key:d[key]))  # Ascar
print(min(d,key=lambda key:d[key]))  # jason

# 4.filter filtering
 Format:	filter(function , iterable)
	function Is the function name, iterable Is an iteratable object
l = [11, 22, 33, 44, 55]
res = filter(lambda x:x>30,l)

# 5.reduce summary
ps:stay python in the future, reduce Not anymore built-in function Inside, need from functools import reduce.
format	reduce(function,sequence [ ,initial] )
	function Is the function name, function Must be two parameters in, sequence Is a sequence, initial Having a specified value is equivalent to appending usage data, or when sequence Null as the return value.
List summation
from functools import reduce
d = [11, 22, 33, 44, 55, 66, 77, 88, 99]
res = reduce(lambda x, y: x + y, d)
Factorial of realization 6
from functools import reduce
res = reduce(lambda x, y: x * y,[x for x in range(1,7)])

List of built-in functions

function describe example
abs() Find absolute value abs(123)/abs(-123)
all() Judge whether all elements in the given iteratable parameter iterable are TRUE The return value of empty tuple and empty list is True
any() Judge the given parameters. If one of the parameters is True, it is True l = [1,2,0] print(any(l))>>True
bin() Binary conversion bin(10)
oct() Octal conversion oct(10)
hex() Hexadecimal conversion hex(10)
bytes() Code conversion res = 'Allen' print(bytes(res,'utf8'))
str() String conversion str(1)
encode() code 'Allen'. encode('utf8 ')
decode() decode b'\xe8\x89\xbe\xe4\xbc\xa6'.decode('utf8')
callable() Is it callable def index(): pass print(callable(index))>>True
chr() Match ASCII codes according to numbers chr(65)>>>A
ord() Match numbers according to ASCII code ord('A')>>>65
complex complex complex(1+2j)
dir() View the callable names of the current object Dir (calling object)
divmod() paging Use the remainder to determine whether additional paging divmod is required (102,10)
eval() Only simple syntax in strings is recognized Recognize simple syntax and execute
exec() Syntax for identifying complex points in strings Recognize complex syntax and execute
isinstance() Determine whether the object belongs to a data type isinstance(123,int) >>>True
pow() exponentiation pow(2,3)>>>8
round() rounding round(8.5)>>>8


  • Iteration means updating. Each update must rely on the results of the previous iteration

ps: iteration provides us with a way that does not depend on index values

  • Iteratable object

Generally speaking, the built-in methods include__ iter__ Methods can be called iteratable objects
Contains strings, lists, tuples, dictionaries, collections, and file objects

__ iter__ There is also a simple way to write iter() when calling the method
Generally, all double drop methods will have a corresponding simplified version method name ()

d = {'username':'alan','pwd':123}
print(d.__iter__())  # Get is the key of the dictionary
  • Iterator objects

In short, it contains__ iter__ The method also contains__ next__ method
The file object does not need to be converted, and is itself an iterator object
Other types of iteratable objects require__ iter__ Transform it

Why is it necessary to create an iterator object?

One of the most important factors is to find a function that can achieve value without relying on index

d = {'username':'alan','pwd':123}
res = iter(d)
print(next(res))  # username
print(next(res))  # pwd
print(next(res))  # When the element is retrieved, an error will be reported

for loop essence

l1 = [1,2,3,4,5,6,7,8,9,11,22,33,44,55]
# It is required to print every element in l1 in a loop, but the for loop cannot be used__ next__()  next()
res = l1.__iter__()
while True:
	print(res.__next__())  # It is obvious that in this step, the loop continues all the time. After all elements are fetched, an error is reported directly. Therefore, an exception capture operation is added in this step
Method 1:
n = 0
while n < len(l1):
	n += 1
 Method 2:
d = {'name':'alan','pwd':123,'hobby':'read'}
res = d.__iter__()
while True:
	except StopIteration as e:

Exception capture

  • What is exception capture

An error in code operation will lead to an exception. If there is no corresponding solution after the exception, the whole program will end directly

  • Three important components of anomalies


Error location, turn to the bottom of the prompt information, click the link, and directly challenge the corresponding location of the error
Error type
3. Type after error type
This is the detailed reason for the error report (very important, many problems can be solved according to this)

  • Types of errors

syntax error

This situation is not allowed. Once it occurs, it should be corrected immediately
Logical error
It can be allowed, but try to avoid it

  • Exception capture basic syntax
	Error prone code
except Error type as e:
	Corresponding processing mechanism after error(e Refers to the details of the error)
except Error type as e1:
	Corresponding processing mechanism after error(e Refers to the details of the error)
except Error type as e2:
	Corresponding processing mechanism after error(e Refers to the details of the error)
Universal exception handling Exception
    # int('abc')
    # l = [11]
    # l[100]
except Exception:
    print('Whatever you come, it doesn't matter')

Exception capture sentence patterns and universal exceptions
    1.Code that may have errors needs to be monitored
    2.The less code to be monitored, the better
    3.The lower the frequency of exception capture, the better
  • Exception capture full version
	Detected code
except Error type as e:
	The command executed when the detected code does not report an error
	Whether an error is reported or not, it will be executed

# assert
name = 'alan'
assert isinstance(name,str)

# Active error reporting
raise Error type

Summary of iterator and index values

Iterative value
		1.A general value taking method independent of index
		1.The order of values is always fixed and cannot be obtained repeatedly from left to right
 Index value
		1.You need to provide an ordered container type to get the value(Not a universal way)
		1.Values can be repeated


  • What is a generator

The generator is essentially a custom iterator with the named keyword yield

# The definition stage is an ordinary function
def my_ge():
    yield 123, 152
    yield 'alan'
res = my_ge()  # Call the function for the first time and turn the function into a generator
ret = res.__next__()  # first, each time you execute next, the code runs to yield to stop and return the following parameters
print(ret)  # (123, 152)
ret = res.__next__()  # second
print(ret)  # alan
  • The essence of range function
def my_range(start, stop=None, step=1):
    if not stop:
        stop = start
        start = 0
    while start < stop:
        yield start
        start += step

for i in my_range(5):
  • yield value
def eat(name):
	print('%s Ready to cook!!!' %name)
	while True:
		food = yield
		print('%s I am eating%s'% (name,food))
res = eat('alan')
  • yield vs return
    1.Can return value(Multiple are supported and organized into meta groups)
    2.Function body code encountered yield Not over, but"Stop"
    3.yield You can turn functions into generators and also support external value transfer
    1.Can return value(Multiple are supported and organized into meta groups)
    2.Function body code encountered return Direct end
  • Generator Expressions
l = [11, 22, 33, 44, 55, 66, 77, 88, 99]
res1 = (i+1 for i in l if i!=44)

Posted on Wed, 01 Dec 2021 21:37:47 -0500 by maseeha