What are the advanced features of Python?

Source: Internet
Author: User
Tags iterable

This article and everyone to share is mainly Python development in some of the new features, come together to see it, I hope to help you.

List-generation (comprehensions)

Slices and iterations do not say, here directly first look at the list of the formula, from the name can probably guess this is a list of methods to generate, such as: how to generate [1*1, 2*2, ..., 10*10]? You can use loops to add elements to the end of the list, if you use the Pythonic method, which is the list-generated type:

>>> [x * x for x in range (1, 11)]

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

The following can also be followed if the judgment, for example:

>>> [x * x for x in range (1, one) if x%2==0]

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

In this way, you would have to use the loop to write 4, 5 lines of code, using a line to solve, intuitive and clear.

You can also use two for loops to generate a full array:

>>> [M + N for m in ' ABC ' for n in ' XYZ ']

[' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']

How do you add an if judgment? Can be added after each for statement, or at the end of the add:

>>> [M + N for m in ' ABC ' if M < ' C ' for n ' XYZ ' if n < ' Z ']

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

[' AX ', ' AY ', ' BX ', ' by ']

You can also iterate over multiple variables in a for statement, such as Dict's items () to iterate both key and value at the same time:

>>> d = {' X ': ' A ', ' y ': ' B ', ' z ': ' C '}>>> [k + ' = ' + V for K, V in D.items ()]

[' Y=b ', ' x=a ', ' z=c ']

That's almost it.

But before always write C + +, this mode of thinking is difficult to change, only slowly in the use of familiar with this grammar, accustomed to be able to write in the subconscious.

Generator (Generator)

Why use generators? Liao Da's tutorial is very detailed, here again briefly:

1. Because the contents of the list are in memory and are subject to memory limitations, the list has limited capacity.

2. If we only access a very small number of elements, then there is great space waste.

3. While the generator can compute the next value on one side of the iteration, theoretically, the process can go on indefinitely without consuming a lot of memory.

Here is a brief introduction, in more detail please Google ha ~

How do I create a generator? The first method is similar to the list generation mentioned earlier, just to change [] to ():

>>> L = [x * x for x in range]]>>> l

[0, 1, 4, 9, (+), 81]>>> g = (x * x for x in range) >>> g

<generator Objectat 0x1022ef630>

As you can see, the method is roughly the same, [] get a list of all the values that have been obtained, () get a generator, they can iterate with a for loop, but the generator cannot use subscript access, and can only be iterated once, again iteration will have stopiteration exception:

>>> for I in G: ... print (i)

... 0149162536496481>>> for I in G: ... print (i)

...>>> Next (g)

Traceback (most recent):

File "", Line 1, in

Stopiteration

But when we create a generator, we basically never call next (), but instead iterate over it with a for loop and don't need to care about Stopiteration's error.

If the computed algorithm is more complex, it can also be implemented with a function like a for loop with a similar list generation, for example, the famous Fibonacci sequence:

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 yield this keyword, I just learned python time also tangled for a long, until the time to see the generator is generally understood, we can generally understand the search, I think this thing said trouble, only say one or two and afraid to say wrong. This is what Liao's tutorial says:

The function is executed sequentially, the return statement is encountered, or the last line function statement is returned. The function that becomes generator, executes at each call to next (), encounters a yield statement return, and executes again from the yield statement that was last returned.

It may be a bit difficult to understand, but it's good to know.

Of course, the function can also add return, in a generator function, if there is no return, then the default execution to the completion of the function, if the return in the execution process, the direct throw stopiteration terminate iteration.

For example, in the example above, we find that the ' done ' string is not present in the iteration because the value of return is treated as Exception value, if it is to be displayed, it can be:

>>> g = fib (6) >>> while True: ... try: ... x = Next (g) ... print (' G: ', x) ... except stopiteration as e: ... Print (' Generator return value: ', E.value) ... break

...

G:1

G:1

G:2

G:3

G:5

G:8

Generator return Value:done

Iterators (Iterator)

An object that can act directly on a for loop is called an iterative object, and you can use the Isinstance () function to determine whether an object can be iterated:

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

An object that can be called by the next () function and continually returns the next value is called an iterator: Iterator. Of course, you can still use Isinstance () to determine whether an object is a iterator object:

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

From the above two examples, it can be understood that the generator and list,tuple,str are iterable objects, the generator is also the Iterator object, and the list is not. Can you directly convert the Iterable object to a 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 flow, we can think of this data flow as an ordered sequence, but not in advance to know the length of the sequence, we can only continuously through the next () function to calculate the next data on demand, so the calculation of Iterator is inert, It is calculated only if you need to return the next data. Iterator can even represent an infinitely large stream of data, but list,tuple what is impossible.

Summarize

After a winter vacation did not touch the code, the equivalent of a review of Ah, in fact, the characteristics of this is very simple, it is not difficult to understand, and so on all almost review finished still have to go deeper, understand more.


Source: Segmentfault

What are the advanced features of Python?

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.