python--list comprehensions, del statements, and generators (generator)

Source: Internet
Author: User
Tags function definition

1. Using the list generation, you can write very concise code

For example:

Squares = []for x in range    ]: squares.append (x**2) print squares# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Can be written in the following form:

Squares = [x**2 for x in range (10)]

The For loop can also be followed by an if statement as a criterion, such as an even number can be obtained

[X**2 for x in range] if x% 2 = = 0]# [0, 4, 16, 36, 64]

You can also use the dual for loop to generate a full array

[M + N for m in ' ABC ' for n ' xyz ']# [' Ax ', ' Ay ', ' Az ', ' Bx ', ' by ', ' Bz ', ' Cx ', ' Cy ', ' Cz ']

List expressions can contain complex expressions and function nesting

From math import pi[str (round (pi,i)) for I in range (1, 6)]# [' 3.1 ', ' 3.14 ', ' 3.142 ', ' 3.1416 ', ' 3.14159 ']

Nested list expressions

[[Row[i] for row under matrix] for I in range (4)]# [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]

The above expression can also be written in the following form:

transposed = []for i in Range (4):    transposed.append ([row[i] for row in matrix]) print transposed# [[1, 5, 9], [2, 6, 10 ], [3, 7, 11], [4, 8, 12]]

This in turn writes the same as follows:

transposed = []for i in Range (4):    transposed_row = [] for    row in matrix:        transposed_row.append (Row[i])    Transposed.append (transposed_row) Print transposed# [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

There is also a python built-in function zip (), also can be implemented as above function

Zip (*matrix) # [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

2.del statement (The DEL statement)

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]>>> del a[0]>>> a[1, 66.25, 333, 333, 1234.5]>>&G T Del a[2:4]>>> a[1, 66.25, 1234.5]>>> del a[:]>>> a[]

The entire list can also be emptied with the following statement

Del A

3. Generator (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]]print l# [0, 1, 4, 9, +,-N,,, 81]g = (x * x for x in range) print g# <gene Rator Object <genexpr> at 0x10f9ba190>

The next return value of generator can be obtained by next ()

Print Next (g) print next (g) print next (g)-------------014

Generator saves the algorithm, each time it is called next(g) , computes g the value of the next element until it is calculated to the last element, no more elements are thrown when the StopIteration error occurs. Of course, this constant invocation is next(g) really too perverted, the right way is to use for loops:

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

So, after we create a generator, we basically never call next() it, but iterate over it through the for loop and don't need to be concerned about StopIteration the error.

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's 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    return ' done ' Print fib (1123581321345589144done)--------------------

As you can see, the fib function is actually a calculation rule that defines the Fibonacci sequence, starting with the first element and extrapolating any subsequent elements, which are actually very similar to generator. In other words, the above functions and generator are only a step away. To turn fib a function into a generator, just print(b) change yield b it to:

def fib (max):    N, a, b = 0, 0, 1 while    n < max:        yield b        A, B = B, a + b        n = n + 1

This is another way to define generator. If a function definition contains a yield keyword, then the function is no longer a normal function, but a generator:

f = fib (a) Print F----------------<generator object fib at 0x107cdad20>

Generator and functions do not have the same execution flow. 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 .

python--list comprehensions, del statements, and generators (generator)

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.