程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

This article thoroughly explains Python list derivation, iterators, generators, and anonymous functions

編輯:Python

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

1、 Anonymous functions (lambda)

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]

2、 The derived type (comprehensions)

list , Derivations can be used in both dictionaries and collections .

List derivation

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]

Dictionary derivation

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}

Set derivation

{
x**2 for x in [1, 1, 2]}# Sets are not allowed to repeat 

{1, 4}

3、 iterator (Iterator)

Iteratable object (Iterable)

python Objects in the , As long as there is a method __iter__ and __getitem__ It's iterative objects , Iteratable objects can provide iterators .

iterator (Iterator)

Defined __next__ Methodical python object .

Determine whether the object is an iteratable object or iterator

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

iteration (Iteration)

Use a loop to iterate over a python Object time , This process is called iteration .

4、 generator (Generators)

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 :

( ) Bounding list derivation generation

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

Add... To the custom function yield Keyword builder

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 

Recommended articles

  • 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 )

Technical communication

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

  • The way ①、 Send the following picture to wechat , Long press recognition , The background to reply : Add group ;
  • The way ②、 Add microsignals :dkl88191, remarks : come from CSDN
  • The way ③、 WeChat search official account :Python Learning and data mining , The background to reply : Add group


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved