Some advanced features of python

Source: Internet
Author: User
Preface I have been using python for more than half a year. since the summer vacation last year, I started to use python for many jobs, C ++ is basically abandoned. However, I am still a little impatient and can write some short code, but... preface

I have been using python for more than half a year. since the summer vacation last year, I started to use python for many jobs, C ++ is basically abandoned. But I am still a little impatient and can write some short code, but I don't know or forget many of python's features. here I will go back to Liao's tutorial to review it, by the way, let's record what I think is important.

Start

This article mainly records the content of the section "advanced features" in the Liao University tutorial and writes down some of my understandings. In my opinion, these features are very pythonic, and they are very bigger in code ~

List generator)

Slice and iteration will not be mentioned. here, let's take a look at the list generative formula. we can guess from the name that this is a method for generating the list, for example, how to generate a list.[1*1, 2*2, ... ,10*10]? You can add elements to the end of the list in a loop. if you use the pythonic method, that is, the list generation formula, it is:

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

It can be followed by the if statement, for example:

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

In this way, four or five lines of code need to be written cyclically, and one line is used to solve the problem, which is intuitive and clear.

Two for loops can also be used to generate a full arrangement:

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

In this way, how can I add if statements? You can add after each for statement, or add at the end:

>>> [m + n for m in 'ABC' if m < 'C' for n in 'XYZ' if n < 'Z']['AX', 'AY', 'BX', 'BY']>>> [m + n for m in 'ABC' for n in 'XYZ' if n < 'Z' and m < 'C']['AX', 'AY', 'BX', 'BY']

You can also iterate multiple variables in a for statement at the same time. for example, the items () of dict can iterate both key and value:

>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }>>> [k + '=' + v for k, v in d.items()]['y=B', 'x=A', 'z=C']

This is almost the case ~

However, in the past, C ++ was always written. this kind of thinking mode is difficult to change. it can only be written in the subconscious when you are familiar with this syntax.

Generator)

Why use a generator? Liao Da's tutorial is very detailed. here I will briefly describe it:

  1. Because the content of the list is stored in the memory, the size of the list is limited due to memory restrictions.

  2. If we only access few elements, there is a huge waste of space.

  3. The generator can calculate the next value while iteration. Theoretically, this process can be performed infinitely without occupying a large amount of memory.

Here is a brief introduction. For more details, please Google ~

How to create a generator? The first method is similar to the list generator mentioned above. you only need to change []:

>>> L = [x * x for x in range(10)]>>> L[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]>>> g = (x * x for x in range(10))>>> g
 
   at 0x1022ef630>
 

We can see that the methods are roughly the same. [] gets a list of all values that have been obtained, () gets a generator, and they can all use the for loop for iteration, however, the generator cannot use subscript access and can only be iterated once. if it is iterated again, there will be an exception in StopIteration:

>>> for i in g:...     print(i)...0149162536496481>>> for i in g:...     print(i)...>>> next(g)Traceback (most recent call last):  File "
 
  ", line 1, in 
  
   StopIteration
  
 

However, after we create a generator, we will never call next (), but iterate it through the for loop without worrying about the StopIteration error.

If the calculated algorithm is complex and cannot be implemented using a for loop similar to the list generator type, you can also use functions. for example, the famous Fibonacci series:

def fib(max):    n, a, b = 0, 0, 1    while n < max:        yield b        a, b = b, a + b        n = n + 1    return 'done'

About the yield keyword, I had struggled for a long time when I was just learning python. I didn't understand it until I saw the generator. you can search for it to understand it, I think it is troublesome to say this thing. I only say one or two sentences and I am afraid of making a mistake. This is what Liao said in his tutorial:

The function is executed sequentially. if a return statement or the last row of the function statement is returned. The generator function is executed every time next () is called. when the yield statement is returned, the yield statement returned last time is executed again.

It may be a bit difficult to understand, but it is easy to understand.

Of course, you can also add return to the function. in a generator function, if no return exists, the function is executed until the function is complete by default. if return is executed, the StopIteration is directly thrown to terminate the iteration.

For example, in the above example, we found that the 'done' string does not appear during iteration because the return Value is treated as the Exception Value. to display it, we can do this:

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

Objects that can directly act on the for loop are called iteratable objects. you can use the isinstance () function to determine whether the objects can be iterated:

>>> from collections import Iterable>>> isinstance([], Iterable)True>>> isinstance({}, Iterable)True>>> isinstance('abc', Iterable)True>>> isinstance((x for x in range(10)), Iterable)True>>> isinstance(100, Iterable)False

The object that can be called by the next () function and continuously return the next value is called the Iterator: Iterator. Of course, you can still use isinstance () to determine whether an object is an Iterator object:

>>> from collections import Iterator>>> isinstance((x for x in range(10)), Iterator)True>>> isinstance([], Iterator)False>>> isinstance({}, Iterator)False>>> isinstance('abc', Iterator)False

The above two examples show that the generator, list, tuple, and str are both Iterable objects, the generator is also an Iterator object, and the list is not. Can I directly convert an Iterable object to an Iterator object?

You can use the iter () function:

>>> isinstance(iter([]), Iterator)True>>> isinstance(iter('abc'), Iterator)True

In fact, the Iterator object represents a data stream. we can regard this data stream as an ordered sequence, but we cannot know the sequence length in advance. we can only continue to pass next () function compute computes the next data as needed. Therefore, the Iterator computation is inert and will only be calculated when the next data needs to be returned. Iterator can even represent an infinitely large data stream, but list, tuple or something is impossible.

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.