Advanced features of Python (slices, iterations, generators, iterators)

Source: Internet
Author: User
Tags iterable javascript array

By mastering Python's data types, statements and functions, you can basically make a lot of useful programs.
But in Python, not as much as the code, the more complex the better, the simpler the better.
Based on this idea, some of the advanced features of Python are extended.

Slice

In Python, it is a very common operation to take a list or a subset of the tuple elements.

L = ["gege","gege","egye"];[L[0],L[1],L[2]]

The above is a stupid way, because the extension, take the first n elements there is no way.

r = []n = 3for i in range(n):    r.append(i)

There is also this operation, which often takes the specified index range, which is cumbersome to use, so Python provides the slice (Slice) operator, which greatly simplifies this operation. A slice method that resembles an array in JavaScript.

The slice method in a JavaScript array

It can create a new array based on one or more items in the current array. The slice () method can accept one or two parameters, that is, the starting and ending positions of the item to be returned.
In the case of only one argument, the slice method returns all items starting at the specified position of the parameter to the end of the current array.
If there are two parameters, the method returns the entry between the start and end positions, but excludes the item at the end position.
Note: The slice method does not affect the original array.
For the above question, you want to take the first three elements. Use it directly.

L[0:3]//也可以省略0:L[:3]

Similarly, the Python array supports a negative index, and the slice also supports a reciprocal slice, remembering that the index of the first element of the countdown is-1.
You can also take a discontinuous number

L = list(range(100));L[:10] //   前10个数L[-10:] //后10个数L[:10:2] //前10个数,每两个取一个L[:] //原样复制一个list

Tuple is also a list, the only difference is that a tuple is immutable, so a tuple can also use the slice operation, but the result of the operation is still a tuple.

(0,1,2,3,4)[:3]//(0,1,2)

The string ' xxxx ' can also be seen as a list, where each element is a character, so the string can also be sliced, just the result of the operation or the string

“ffeefg”[:3]

In fact, other programming languages also have a lot of operations on strings, such as substring, the purpose is to slice the string, Python has no interception function for the string, only need a slice operation can be done, very simple.

Iteration

In Python, an iteration is manipulated by a for ... in loop, not only on a list or a tuple, but also on other objects that can be iterated.

//dictd = {‘a‘:1,‘b‘:2,‘c‘:3}for key in d:    print(key)for value in d.values():    print(value)for k,v in d.items():    print(k,v)//字符串for ch in ‘abc‘:    print(ch)

When using a For loop, no matter what the data type is, as long as it is an iterative object, how can you tell if it is an iterative object?
Use the iterable type of the collections module to determine

from collections import Iterableisinstance(‘abc‘,Iterable) //true# str是否可迭代isinstance([1,2,3],Iterable) //true# list是否可迭代isinstance(123,Iterable) //false# 整数是否可迭代

Python's built-in enumerate function can turn a list into an index-element pair so that the index and the element itself can be iterated at the same time for the For loop.

for i,value in enumerate([‘s‘,‘ss‘,‘sss‘]):    print(i,value)
List-Generated
[x*x for x in range(1,11)]//把要生成的元素放在前面[x*x for x in range(1,11) if x%2 == 0]//for循环后面还可以加上if判断[m+n for m in ‘ABC‘ for n in ‘XYZ‘]//[‘AX‘, ‘AY‘, ‘AZ‘, ‘BX‘, ‘BY‘, ‘BZ‘, ‘CX‘, ‘CY‘, ‘CZ‘]//可以使用两层循环,生成全排列三层以及三层以上就很少用
Generator (Generator)

List generation takes up a lot of space when the list size is large
So the generator comes in handy, cycle through the calculation mechanism
The first method of defining generator,

 g = (x * x for x in range(10))for n in g:    print(n)

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

The famous Fibonacci series

The second way to define generator

def fib(max):    n,a,b = 0,0,1    while n < max:       // print(b)         yield b        a,b = b,a+b        n = n + 1

Change the print (b) above to yield B, which is a generator.

Advanced features of Python (slices, iterations, generators, iterators)

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.