Original Advanced features of Python introductory learning

Source: Internet
Author: User
Tags iterable

A preface

There may be some difficulty in learning advanced features, these new features have not been encountered in the previous C/s + +, and C + + does not support such simple but powerful syntax.

Two slices

When it comes to slicing, you can imagine cutting a radish and getting a section of the radish, using this analogy to describe the section here is very appropriate. The slice operation in Python is to take a list or a section of a tuple.

For example, a list with the following definitions:

#define a listl=[' Luffy ', ' Corey ', ' Nancy ', ' Jeffrey ', ' Kyle ', ' Avery ', ' Jason ', ' Sunny '

There are two ways to take the first 3 elements, the code is as follows:

>>> l[:3][' Luffy ', ' Corey ', ' Nancy ']>>> l[0:3][' Luffy ', ' Corey ', ' Nancy '

In other words, starting from 0 can be omitted.

The code to take the 2nd to 4th element is as follows:

>>> l[1:5][' Corey ', ' Nancy ', ' Jeffrey ', ' Kyle ']

Take the 2nd to the bottom until the last code is as follows:

>>> l[-2:][' Jason ', ' Sunny ']

To take the entire list without knowing the list length, the code is as follows:

>>> l[:][' Luffy ', ' Corey ', ' Nancy ', ' Jeffrey ', ' Kyle ', ' Avery ', ' Jason ', ' Sunny '

Take 1 of each 2 in the entire list:

>>> l[::2][' Luffy ', ' Nancy ', ' Kyle ', ' Jason '

Each of the top 6 in the list takes 1 of the 2:

>>> l[:5:2][' Luffy ', ' Nancy ', ' Kyle '

In the actual editing code, it is often possible to replace the variable that points to list in the slice operation here with the list itself, as follows:

>>> [' Luffy ', ' Corey ', ' Nancy ', ' Jeffrey ', ' Kyle ', ' Avery ', ' Jason ', ' Sunny '][:3][' Luffy ', ' Corey ', ' Nancy ']

Both tuple and string can be considered as a list, so the above syntax can also be used for it.

Three-list generation

List Comprehensions is a very powerful build built into python that is used to create lists.

For the simplest example, we're going to create a list from 1 to 10 that can be used

List (range (1,11))

This simple line of code is done. But what if you want to build a more complex list?

What should I do to build a list such as [1x1,2x2,3x3,..., 10x10]? The use of loops is of course achievable, but the code is too complex, and using list generation requires only the following line of code:

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

If you add only the square of an even number, it is not complicated, just add the IF condition after the for loop.

>>> [x*x for x in range (1,11) if x% 2 = = 0][4, 16, 36, 64, 100]

You can also use the two-layer loop,

>>> [x+y for x in ' ABC ' for y in ' XYZ ' [' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']

Writing so many list-building, I think we all understand the origin of this grammar. In fact, the normal grammar is reversed, the innermost calculation is placed at the front. As the last list generation can be written as normal syntax:

For x in ' ABC ': for y in ' XYZ ':p rint (x+y)

Quad Generator

With list generation, we can create a list directly, but we can't create a list with a lot of elements when we think about memory constraints, so what do we do now?

Python provides a mechanism called a generator that can extrapolate subsequent elements through the generator, so that you don't have to create all the elements at once. There are two ways to create a generator:

The first method: changing the [] list generation to ()creates a generator.

As shown in the following code:

>>> g= (x for x in range) >>> print (Next (g)) 0

To get the first element of the generator, you can call the next function directly on G. Of course, you can also use a for loop to traverse the next generation of data from the entire generator.

The second method: If the calculated method is too complex, the list generation cannot be implemented, it can be implemented by a function. Relative to generator from the list, from the function to the generator is also very simple, just need to write the function first, and then add the yield keyword in a location.

For example, the function of generating a Fibonacci sequence is as follows:

def fib (max):    N, a, b = 0, 0, 1 while    n < max:        print (b)        A, B = B, a + b        n = n + 1    return ' done '

To convert this function to generator, simply replace the print (b) line with 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 ' do Ne

The function that contains the yield keyword is no longer a function, but a generator. It is important to note that the generator execution process is not the same as the function, returns when yield is encountered, and resumes from the yield where it was last returned the next time it is called.

Five iterators

An object that can directly act on a for loop is called an iterative object: iterable, you can use Isinstance () to determine whether an object is a Iterable object. The generator can be traversed not only by a for loop, but also by using next (). We refer to an iterator that can be called by the next () function and constantly return the next value: Iterator.

Here to distinguish between a iterable and a iterator,list,dict,str are iterable, but not iterator (you can use the ITER () function to turn iterable into iterator). Iterator can be an infinite stream of data that cannot know the length of the entire sequence in advance, and these are requirements that iterable cannot meet.

Six PostScript

Here are some of the new features of programming that I learned in Python. If there is a mistake, please leave a message!!!

  

  

Original Advanced features of Python introductory learning

Related Article

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.