Detailed explanation python3 Anonymous functions 、 The derived type 、 Iterator and generator usage .
I understand it as a simple way to define functions , No need to use def Keywords define functions . grammar :lambda Parameters : Operation parameter expression .
add = lambda x, y: x + y
print(add(3, 5))
8
list(map(lambda x, y: x + y, range(-2, 2), range(1, 5)))
# Pass in two iterable object range(-2, 2), range(1, 5)
[-1, 1, 3, 5]
list , Derivations can be used in both dictionaries and collections .
A simple way to create a list .
#if The statement is placed in for after
In [29]: [x for x in range(1, 11) if x % 2 == 0]
# about range(1, 11) Each element in , Can be 2 The output of an integer division makes up a new list
Out[29]: [2, 4, 6, 8, 10]
#if The statement is placed in for You can use else
In [30]: [x if x % 2 == 0 else -x for x in range(1, 11)]
# about range(1, 11) Each element in , Can be 2 The original value of the output of an integer division , If the original value is negative and cannot be divided, it will be output , Form a new list
Out[30]: [-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
{k:v for k,v in mcase.items()}
{'a': 10, 'b': 34, 'A': 7, 'Z': 3}
{x**2 for x in [1, 1, 2]}# Sets are not allowed to repeat
{1, 4}
python Objects in the , As long as there is a method __iter__ and __getitem__ It's iterative objects , Iteratable objects can provide iterators .
Defined __next__ Methodical python object .
from collections.abc import Iterable, Iterator
def g():
yield 1
yield 2
yield 3
# Is it python Iteratable object judgment
print('Iterable? [1, 2, 3]:', isinstance([1, 2, 3], Iterable))#isinstance() Determine whether an object is Iterable object
print('Iterable? \'abc\':', isinstance('abc', Iterable))
print('Iterable? 123:', isinstance(123, Iterable))
print('Iterable? g():', isinstance(g(), Iterable))
# Is it python The iterator determines
print('Iterator? [1, 2, 3]:', isinstance([1, 2, 3], Iterator))#isinstance() Determine whether an object is Iterator object
print('Iterator? iter([1, 2, 3]):', isinstance(iter([1, 2, 3]), Iterator))
print('Iterator? \'abc\':', isinstance('abc', Iterator))
print('Iterator? 123:', isinstance(123, Iterator))
print('Iterator? g():', isinstance(g(), Iterator))
Iterable? [1, 2, 3]: True
Iterable? 'abc': True
Iterable? 123: False
Iterable? g(): True
Iterator? [1, 2, 3]: False
Iterator? iter([1, 2, 3]): True
Iterator? 'abc': False
Iterator? 123: False
Iterator? g(): True
Use a loop to iterate over a python Object time , This process is called iteration .
Generator is also an iterator , however , It can only be iterated once . This is because they don't store all the values in memory ( Can save a lot of memory ), Instead, it loops and generates values ( The generator saves the algorithm , You can calculate the value of the next element ), The method to create the generator is as follows :
g = (x * x for x in range(10))# Only one iteration , Store algorithm only , Not all elements will be generated and stored in memory .
g
<generator object <genexpr> at 0x000002B53772C4C0>
for i in g:#for Cycle through the elements in each generator , When executing the output nothing( Only one iteration , Store algorithm only )
print(i)
0149162536496481
When the calculation algorithm is very complex, the user-defined function is used . for instance , Generator for calculating Fibonacci sequence .
def fibon(n):
a = b = 1
for i in range(n):
yield a# This function is a generator
a, b = b, a + b
for x in fibon(1000000):
print(x) # Don't worry that it will use a lot of resources
Reference material
https://www.liaoxuefeng.com/wiki/1016959663602400/1017318207388128
Intermediate Python
-END-
Past highlights
It is suitable for beginners to download the route and materials of artificial intelligence ( Image & Text + video ) Introduction to machine learning series download Chinese University Courses 《 machine learning 》( Huang haiguang keynote speaker ) Print materials such as machine learning and in-depth learning notes 《 Statistical learning method 》 Code reproduction album machine learning communication qq Group 955171419, Please scan the code to join wechat group