Hello everyone , In the use of Python Anonymous functions are often encountered 、 The derived type 、 Iterators and generators , These methods are very important . Today I give you a one-time will understand , Like to remember to collect 、 Focus on 、 give the thumbs-up .
notes : Technical exchange is provided at the end of the article 、 Experience sharing 、 Information
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 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
Li Hongyi 《 machine learning 》 Mandarin Program (2022) coming
Some people made Mr. Wu Enda's machine learning and in-depth learning into a Chinese version
Addicted to , Recently, a large visual screen has been rolled out for the company ( Source code attached )
So elegant ,4 paragraph Python Automatic data analysis artifact is really fragrant
Combing for more than half a month , Well prepared 17 A map of knowledge and thinking , Let's talk about statistics this time
Year end summary :20 Visual large screen template , Direct application is really fragrant ( The source code is attached at the end of the article )
Welcome to reprint 、 Collection 、 Gain some praise and support ! data 、 The code can be obtained from me
At present, a technical exchange group has been opened , Group friends have exceeded 2000 people , The best way to add notes is : source + Interest direction , Easy to find like-minded friends