Home > Backend Development > Python Tutorial > Advanced features for getting started with Python

Advanced features for getting started with Python

黄舟
Release: 2016-12-16 16:34:42
Original
1381 people have browsed it

Preface

You may find it a little difficult when learning advanced features. These new features have not been encountered in c/c++ before, and c/c++ does not support such a simple but powerful syntax. .

II Slicing

When it comes to slicing, you can imagine cutting a radish and getting a certain section of the radish. This is a very appropriate metaphor for slicing here. The slicing operation in python is to take a certain segment of the list or tuple.

 For example, there is a list defined as follows:

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

There are two ways to get the first three elements. The code is as follows:

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

In other words, if you start from 0, you can omit it.

 The code to get the 2nd to 4th elements is as follows:

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

The code for taking the second to last item until the last one is as follows:

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

  Get the entire list without knowing the length of the list The content, the code is as follows:

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

Take 1 out of every 2 in the entire list:

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

 Take 1 of every 2 of the first 6 items in the list:

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

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

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

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

三 List generation

List generation (List CompRehensions) is a very powerful generation built into python for creating lists.

 The simplest example, we want to create a list from 1 to 10, which can be done with a simple line of code like

list(range(1,11))

. But what about generating more complex lists?

 What should we do to generate a list like [1x1, 2x2, 3x3,...,10x10]? Of course it can be achieved using loops, but the code is too complicated. Using list generation only requires 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 even numbers, 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 a two-level loop ,

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

Having written so many list generation expressions, I think everyone understands the origin of this syntax. In fact, it is to reverse the normal syntax and put the innermost calculation first. For example, the last list generation can be written as the following normal syntax:

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

Four generators

With the list Generatively, we can directly create a list, but if we consider memory limitations, we cannot create a list with a large number of elements. So what should we do at this time?

 Python provides a mechanism called a generator. The generator can be used to calculate subsequent elements, so that you don’t have to create all the elements at once. To create a generator, there are two methods:

The first method: change [] in the list generation expression to () to create a generator.

 As shown in the following code:

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

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

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

 For example, the function that generates a Fibonacci sequence is as follows:

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

To convert this function into a generator, you only need to replace the line (b) line to yield B.


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


A function containing the yield keyword is no longer a function, but a generator. It should be noted that the execution flow of the generator is different from that of the function. It returns when it encounters a yield, and continues execution from the last returned yield the next time it is called.

Five Iterators

Objects that can be directly used in for loops are collectively called iterable objects: Iterable. You can use isinstance() to determine whether an object is an Iterable object. Generators can be traversed not only by for loops, but also by using next(). We call objects that can be called by the next() function and continuously return the next value collectively called iterators: Iterator.

  Here we need to distinguish between an Iterable and an Iterator. List, dict, and str are all Iterable, but not Iterator (you can use the iter() function to turn Iterable into Iterator). Iterator can be an infinite data stream, and the length of the entire sequence cannot be known in advance. These are requirements that Iterable cannot meet.

Six Postscript

What are mentioned here are some new programming features that I only learned in python. If there are any errors, please leave a message! ! !

The above is the content of advanced features for introductory learning of Python. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template