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

Explain Python list derivation | iterator | generator | anonymous function

編輯:Python

author | pythonic Biological man

source | pythonic Biological man

 Detailed explanation python3 Anonymous functions 、 The derived type 、 Iterator and generator usage .

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

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 

Reference material

https://www.liaoxuefeng.com/wiki/1016959663602400/1017318207388128
Intermediate Python

Looking back

Matplotlib Two methods of drawing torus !

13 individual python Necessary knowledge , Recommended collection !

Artifact , Easy visualization Python Calling process !

Low code out of half a lifetime , Come back or " cancer "!

 Share
Point collection
A little bit of praise
Click to see 

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