Top ten advanced features of python_Python advanced features

Reduce code and improve efficiency

1. Slicing

take part of a sequence

L [ start : end : step ] with head but without tail

1 #!/usr/bin/python3

2 #-*- coding:utf-8 -*-

3

4 L = [ 1, 3, 6, 9, 45, 66]5

6 print ( L[:4] ) # Equivalent to L[0:4] slice subscript 0 ~ 3

7 print ( L[-2:] ) #The penultimate slice starts from the penultimate 2 and cuts back to the penultimate and the penultimate first

8 print ( L[:5:2] ) #The first 5 numbers, one for every 2

9 print ( L[::5] ) #All numbers, one for every 5

c564f658779cdd696ccd24c465f06c51.png

L[ : : -1] Backcut

2. Iteration

In Python, iteration is done with for...in, while in many languages ​​iterating over lists is done with subscripting.

Iterates with or without subscripts, such as dict

f343254997a6941ce72fd948a5b21f78.png

The dict is not stored in order, and the order of the iterated results is likely to be different

dict iterates over key by default. To iterate over value:

86f10768098eb7969aaea054e6cd0320.png

Iterate over both key and value:

dbb4fa4eddcb857c625d5dcb3e3cb5bb.png

Determine whether it is possible to iterate

a79dd9c735a50be6074bb0a1a61581cb.png

3. Iterator

Iteration is one of Python's most powerful features, a way of accessing the elements of a collection.

All objects that can act on the for loop are of the Iterable type, that is, the iterable object

All objects that can act on the next() function are of type Iterator, that is, an iterator, which represents a sequence of lazy calculations (it will only be calculated when the next data needs to be returned)

Iterator objects are accessed from the first element of the collection until all elements have been accessed. Iterators can only go forward and not backward.

Iterators have two basic methods: iter() and next().

Collection data types such as list, dict, str, etc. are iterative objects, but not iterators. An iterator object can be obtained through the iter() function

String, list or tuple objects can all be used to create iterators

Iterator objects can be iterated over using a regular for statement:

1 #!/usr/bin/python3

2 #-*- coding:utf-8 -*-

3

4 list = [1, 2, 3, 4]5 it = iter(list) #Create an iterator object

6

7 for x init:8 print(x, end=" ") #不换行输出

91f39bc88d4eae811d06c78c4c944a9e.png

也可以使用 next() 函数:

1 #!/usr/bin/python3

2 #-*- coding:utf-8 -*-

3

4 list = [1, 2, 3, 4]5 it = iter(list) #创建迭代器对象

6

7 whileTrue:8 print (next(it))

8853ff5f741869473d5d388e83853977.png

StopIteration

StopIteration 异常用于标识迭代的完成,防止出现无限循环的情况

4.列表生成式

简单却强大的可用来创建list的生成式

如:生成一个列表 [1x1,  2x2,  3x3,  ...,  10x10]

用循环做

1 #!/usr/bin/python3

2 #-*- coding:utf-8 -*-

3

4 L =[]5 for x in range(1,11):6 L.append(x*x)7 for i inL[:]:8 print (i, end = " ")

用列表生成式做

1 #!/usr/bin/python3

2 #-*- coding:utf-8 -*-

3

4 L = [ x*x for x in range(1,11)]5

6 for i inL[:]:7 print (i, end = " ")

d88c5b11eec56112ed63d02bfeab79e8.png

列表生成式内还可加 if 判断

1 #!/usr/bin/python3

2 #-*- coding:utf-8 -*-

3

4 L = [ x*x for x in range(1,11) if x%2 ==0 ]5 #筛选出仅偶数的平方

6 for i inL[:]:7 print (i, end = " ")

5b36f2854ad24e75b47f09760d3738f0.png

还可使用两层循坏,如生成一个全排列

1 #!/usr/bin/python3

2 #-*- coding:utf-8 -*-

3

4 L = [ m+n for m in 'ABC' for n in 'XYZ']5 for i inL[:]:6 print (i, end = " ")

299ca45cdc513b7766152f87df4b8e5e.png

5.生成器

通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。

So, if the elements of the list can be calculated according to a certain algorithm, can we continue to calculate the subsequent elements in the process of looping? This saves a lot of space by not having to create a complete list. In Python, this mechanism of computing while looping is called a generator: generator.

In Python, functions that use yield are called generators.

Unlike ordinary functions, a generator is a function that returns an iterator and can only be used for iterative operations. It is easier to understand that a generator is an iterator.

In the process of calling the generator to run, the function will pause and save all current running information every time yield is encountered, return the value of yield, and continue to run from the current position when the next() method is executed next time.

Calling a generator function returns an iterator object.

The following example implements the Fibonacci sequence using yield:

1 #!/usr/bin/python3

2 importsys3

4 def fibonacci(n): #Generator function - Fibonacci

5 a, b, counter = 1, 1, 06 whileTrue:7 if (counter >n):8 return

9 yielda10 a, b = b, a +b11 counter += 1

12

13 f = fibonacci(10) #f is an iterator, returned by the generator

14 whileTrue:15 try:16 print (next(f), end=" ")17 exceptStopIteration:18 sys.exit()

f91313eba8caa15be99ede787f298fdb.png

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324327211&siteId=291194637