[Original] advanced features of getting started with Python, getting started with python

Source: Internet
Author: User

[Original] advanced features of getting started with Python, getting started with python

Preface

When learning advanced features, you may feel a little difficult. These new features have never been met before in c/c ++, c/c ++ does not support such simple but powerful syntax.

 

Secondary slice

When it comes to slicing, we can think of splitting a piece of radish. We can use this to compare the slicing here. In python, the slice operation is to take a segment in the list or tuple.

For example, a list is defined as follows:

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

There are two methods to retrieve the first three elements. The Code is as follows:

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

That is to say, it can be omitted from 0.

The code for getting 2nd to 4th elements is as follows:

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

Take the last 2nd records until the last code is as follows:

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

The Code is as follows:

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

Take one of every two in the entire list:

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

In the first 6 of the list, take 1 for each 2:

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

In the actual editing code, you can often replace the variable pointing to the list in the slicing operation with the list itself, as shown below:

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

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

 

Triplicate

List Comprehensions is a powerful built-in list generator in python.

The simplest example is to create a list from 1 to 10.

list(range(1,11))

This is a simple line of code. But what should I do to generate a more complex list?

What should I do to generate a list like [1x1, 2, 2, 3x3,..., 10x10? Loop can be implemented, but the code is too complex. To use the list generation method, you only need 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 the even number, it is not complicated. You only need to add the if judgment 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 two-layer loops,

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

After writing so many list generators, I think everyone understands the origins of this syntax. In fact, the normal syntax is reversed, and the bottom layer of computing is placed at the top. For example, the last list generator can be written as the following normal Syntax:

for x in 'ABC':for y in 'XYZ':print(x+y)

 

Four generators

With the list generation formula, we can directly create a list. However, if we cannot create a list with a large number of elements considering the memory limit, what should we do?

Python provides a mechanism called generator, which can be used to calculate subsequent elements, so that you do not need to create all elements at a time. There are two methods to create a generator:

Method 1: Change [] of the List generation type to (), and a generator is created.

As shown in the following code:

 

>>> g=(x for x in range(10))>>> print(next(g))0

To obtain the first element of the generator, you can call the next function directly on the G. Of course, you can also use the for loop to traverse the data generated by the generator in the next step.

Method 2: If the calculation method is too complex and the list generation method cannot be implemented, it can be implemented through functions. Compared with the list Generator to Generator, the function to Generator is also very simple. You only need to write the function first, and then add the yield keyword to a certain position.

For example, the function for generating a Fibonacci series 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, you only need to replace the print (B) line of code 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 'done'

 

A function containing the yield keyword is no longer a function, but a generator. It should be noted that the execution process of the generator is different from that of the function. It is returned when yield is encountered, and the execution will continue from the yield returned last time when the next call is made.

 

Five iterators

Objects that can directly act on the for loop are collectively called iteration objects: Iterable. You can use isinstance () to determine whether an object is an Iterable object. The generator can not only traverse through the for loop, but also use next () traversal. The object that can be called by the next () function and continuously return the next value is collectively referred to as the Iterator: Iterator.

Here we need to distinguish between Iterable and Iterator, list, dict, and str. They are both Iterable, but they are not Iterator (you can use iter () function to change Iterable to Iterator ). Iterator can be an infinitely large data stream and cannot know the length of the entire sequence in advance. These are the requirements that Iterable cannot meet.

 

Postscript

I have learned some new programming features in python. If any error occurs, please leave a message !!!

 

  

  

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.