According to Liao Xuefeng python3 tutorial----python Learning Day

Source: Internet
Author: User


List-generation (comprehensions)


The list generation, which is the comprehensions, is a very simple and powerful build of Python built-in that can be used to create lists.

For example, to generate a list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] you can use list(range(1, 11)) :

>>> list (range (1,11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Build [1x1,2x2,3x3,..., 10x10]:

>>> l=[]>>> for x in range (1,11): L.append (x*x)


>>> l[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


Another simplified notation:

>>> [x*x for x in range (1,11)][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

When writing list generation, put the element x*x to the front, followed by the For loop, you can create the list:

>>> [x*x for x in range (1,11) if x%2==0][4, 16, 36, 64, 100]
>>> [M+n for M in ' ABC ' for n ' XYZ ' [' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']

List the files in the current directory:

>>> import os>>> [D for D in Os.listdir ('. ')] [' DLLs ', ' Doc ', ' include ', ' Lib ', ' Libs ', ' LICENSE.txt ', ' NEWS.txt ', ' python.exe ', ' pythonw.exe ', ' README.txt ', ' Scripts ' ', ' Students ', ' tcl ', ' Tools ']


>>> d={' x ': ' A ', ' y ': ' B ', ' z ': ' C '}>>> for K,v in D.items (): Print (k, ' = ', v) x = Az = Cy = B
>>> [k + ' = ' +v for k,v in D.items ()] [' x=a ', ' z=c ', ' y=b ']


To turn a list of characters into lowercase

>>> l=[' Aadss ', ' Bsad ', ' casd ', ' Dasd ']>>> [S.lower () for S in l][' Aadss ', ' Bsad ', ' casd ', ' DASD ']
L1 = [' Hello ', ' world ', ' apple ', none]# expect output: [' Hello ', ' world ', ' Apple ']print (L2) >>> L2=[s.lower () for S in L1 if Isinstance (s,str)]>>> l2[' hello ', ' world ', ' + ', ' apple ']>>> [Isinstance (S,STR) and s.lower () or s for s in l1][' hello ', ' world ', ' + ', ' apple ', none]>>> [S.lower () if Isinstance (S,STR) else s for s in l1][' hel Lo ', ' world ', ' + ', ' apple ', None]

Generator

With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.

So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.


There are a number of ways to create a generator. The first method is simple, as long as a list of the generated formula is [] changed () to create a generator:

>>> l=[x*x for x in range (Ten)]>>> l[0, 1, 4, 9, (+), $, $, a, 81]>>> g= (x*x for x in rang E (Ten)) >>> G<generator object <genexpr> at 0x02c9fc10>


The difference between creating L and G is only the outermost "" and (), L is a list, and G is a generator.

To print each element of a generator we need to use next ():

>>> Next (g) 0>>> next (g) 1>>> next (g) 4>>> next (g) 9>>> next (g) 16>> > Next (g) 25>>> next (g) 36>>> next (g) 49>>> next (g) 64>>> next (g) 81>>> Next (g) Traceback (most recent): File "<pyshell#53>", line 1, in <module> next (g) stopiteration


When the last element is calculated, a stopiteration error is run out.


Of course, this constant invocation is next(g) so perverted that the correct approach is to use for loops, because generator is also an iterative object:

>>> g= (x*x for x in range) >>> for n in G:print (n) 0149162536496481



Generator is very powerful. If the calculated algorithm is more complex, and the loop with similar list generation for cannot be implemented, it can also be implemented with functions.

For example, the famous Fibonacci sequence (Fibonacci), except for the first and second numbers, can be summed up by the top two numbers:

1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The Fibonacci sequence is not written in a list, but it is easy to print it out with a function:

>>> def fib (max): n,a,b=0,0,1 while N<max:print (b) a,b=b,a+b n=n+1 retur N ' Done ' >>> fib (6) 112358 ' Done '


To change the FIB function above to generator, you only need to change print (b) to yield B:

>>> def fib (max):      n,a, b=0,0,1      while n<max:                             yield b                     a,b=b,a+b                            n=n+1            return  ' Done '      &NBSP;&NBSP;>>>&NBSP;F&NBSP;=&NBSP;FIB (6) >>> f<generator object fib  At 0x02c9fd28>>>> for n in f:     print (n) 112358 


The hardest thing to understand is that generator is not the same as the execution of a function. The function is executed sequentially, the statement is encountered return or the last line of the function is returned. The function that becomes generator, executes at each invocation next() , encounters a yield statement return, and executes again from the last statement returned yield .


To give a simple example, define a generator and return the number 1,3,5 in turn:

>>> def Odd (): print (1) yield 1 print (2) yield 3 print (3) yield 5


>>> o=odd () >>> next (O) 11>>> next (Odd ()) 11>>> next (O) 23>>> next (O) 35 >>> Next (O) Traceback (most recent): File "<pyshell#104>", line 1, in <module> next (o) St Opiteration

As you can see, odd it is not a normal function, but a generator, which is interrupted during execution and yield continues execution the next time. After executing 3 times yield , it has not been yield able to execute, so the 4th call will be an next(o) error.


However for , when calling generator with a loop, the return value of the statement that is not generator is found return . If you want to get the return value, you must catch the StopIteration error, and the return value is included in StopIteration the value :

>>> G=fib (6) >>> while True:try:x=next (g) Print (' G: ', X) Except Stopiteration as E:print (' Generator return value: ', e.value) break g:1g:1g:2g:3g : 5g:8generator return Value:done


Iterators

We already know that for there are several types of data that can be directly acting on a loop:

A class is a collection of data types, such as,,, list tuple , and dict set str so on;

One is generator to include the generator and yield the generator function with the band.

These objects, which can be directly applied to for the loop, are called iterative objects: Iterable .

You can use to isinstance() determine whether an object is an Iterable object:

>>> from Collections Import iterable>>> isinstance ([],iterable) true>>> isinstance ({}, iterable) true>>> isinstance (' abc ', iterable) true>>> isinstance ((x for X in range), iterable) True >>> isinstance (100,iterable) False



The generator can not only be used for for loops, but it can also be next() called by the function and return the next value until the last throw StopIteration error indicates that the next value cannot continue to be returned.

An object that can be called by next() a function and continually returns the next value is called an iterator: Iterator .

You can use to isinstance() determine whether an object is an Iterator object:

>>> from collections Import Iterator >>> isinstance ((x to X in range), Iterator) true>>> are Instance ([],iterator) false>>> isinstance ({},iterator) false>>> isinstance (' ASD ', Iterator) False


Generators are Iterator objects, but,, list dict str Though Iterable they are, they are not Iterator . Turn list , dict and str wait for the Iterable Iterator function to be used iter() :

>>> Isinstance (ITER ([]), Iterator) true>>> isinstance (ITER ({}), Iterator) True


Why is the list, dict, str, and other data types not iterator?

This is because the Python iterator object represents a data stream, and the Lterator object can be called by the next () function and constantly return to the next data, knowing that no data is thrown stopiteration error. Yes, you can. This data flow is considered an ordered sequence, but we can not know the length of the sequence in advance, we can only continue to calculate the next block of data on demand by the function next () function, so the calculation of Iterator is inert and is only calculated when the next data needs to be returned.

IteratorIt can even represent an infinitely large stream of data, such as the whole natural number. Using list is never possible to store all natural numbers.


Higher order functions

One of the simplest high-order functions:

>>> def Add (x,y,f): Return f (x) +f (y) >>> Add ( -5,6,abs) 11


Map ()/reduce ()


The map () function accepts two parameters, one is the function, and the other is Iterable,map the passed function to each element of the sequence and returns the result as a new Iterator.


We are going to use the function f (x) = x2, to function on a list[1,2,3,4,5,6,7,8,9], you can do this with map ():

>>> R=map (f,[1,2,3,4,5,6,7,8,9]) >>> next (R) 1>>> list (R) [4, 9, 16, 25, 36, 49, 64, 81]
>>> list (map (str,[1,2,3,4,5,6,7,8,9])) [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']



Reduce ()---> Reduce a function in a sequence [x1,x2,x3,.....] , the function must accept two parameters, and reduce will accumulate the result and the next element of the sequence, the effect is:

Reduce (f,[x1,x2,x3,x4]) =f (f (f (x1,x2), x3), x4)


To calculate the and of a sequence, you can use the reduce implementation:

>>> from Functools import reduce>>> def add (x, y): Return x+y
>>> reduce (add,[1,3,5,7,9]) 25


Of course, you can also use the Python built-in function sum (), there is no need to use reduce.

>>> sum ([1,3,5,7,9]) 25


If you transform the sequence [1,3,5,7,9] into an integer 13579.reduce it will come in handy:

>>> from functools import reduce>>> def fn (x, y): Return x*10+y
>>> reduce (fn,[1,3,5,7,9]) 13579


Filter-----> Python built-in filter() functions for filtering sequences.

Filter () also accepts a function and a sequence. Unlike map (), filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false.

Eg: in a list, delete an even number, leaving only the odd number:

>>> def is_odd (n): Return n%2==1
>>> List (filter (is_odd,[1,2,3,4,5,6,7,8,9)) [1, 3, 5, 7, 9]

To delete a null character in a string:

>>> def not_empty (s): return S and S.strip ()
>>> List (filter (not_empty,[' A ', ' ', ' B ', None, ' C ', '])) [' A ', ' B ', ' C ']



The

Number of postbacks refers to the same number of reads from left to right, and read-to-left, such as 12321 , 909 . Please use filter () to filter out non-return numbers:

>>> print (List (filter (LAMBDA&NBSP;N:STR (n)  == str (n) [:: -1], range (1, 2000))) ) #先把数字转换为字符串, then flip the string, and finally compare [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22,  33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131,  141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242,252,  262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363,  373, 383,393, 404, 414, 424, 434, 444, 454, 464, 474,  484, 494, 505, 515, 525,535, 545, 555, 565, 575, 585, 595,  606, 616, 626, 636, 646, 656, 666,676, 686, 696, 707,  717, 727, 737, 747, 757, 767, 777, 787, 797, 808,818, 828,  838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949,959,  969, 979, 989, 999, 1001, 1111, 1221, 1331, 1441, 1551, &NBSP;1661,&NBSP;1771,&NBSP;1881,&NBSP;1991]


This article is from the "Creative Pilgrim" blog, so be sure to keep this source http://dearch.blog.51cto.com/10423918/1761661

According to Liao Xuefeng python3 tutorial----python Learning Day

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.