Advanced features of python

­ Original link: https://www.liaoxuefeng.com/wiki/1016959663602400/1017323698112640

【slice】

Objective: take a list or some elements of the tuple

L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']

(1) take the first three elements

L [0: 3], represents the index starts from 0 up to 3 ,, the end, but not 3

(2) After taking two elements L [-2: 0], remember index of the first element is the inverse of-1

(3) the number of intervals taken

L = list(range(100))

L [: 10: 2] represents the number of the top 10, each take a two, starting from 0

 

[Iteration]

Objective: Given a list or tuple, we can traverse the list or tuple through the for loop, we call this traversal iteration (Iteration). In Python, it is through an iterative for ... indone.

Iterative array

Example:

L = range (10)

For i in L:

    Print (i)

Dictionary iterations:

dict iteration is key. If you want iteration value, it can be used for value in d.values(), If you want iteration key and value, can be used for k, v in d.items().

 

Multi-parameter iteration:

for x, y in [(1, 1), (2, 4), (3, 9)]:

... print (x, y)

If you want to list the subscript achieve a similar cycle of Java as how to do? Python built-in enumeratefunctions can be turned into a list index - the element right, so that you can at the forsame time iterative loop index and the element itself:

for i, value in enumerate(['A', 'B', 'C']):

...     print(i, value)

 

How to determine an object is iterable it? It is determined by the type Iterable collections module:

from collections import Iterable

isinstance ( 'abc', Iterable) # Returns True or False

 

[Type] list generation

One nested:

for x in range(1, 11):

...    L.append(x)

 

Nested:

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

 

[Iterator]

Objective: To introduce iterators netxt except for the ()

next()Function continues to call and returns the next value, until the last throw StopIterationerror said it could not continue to return the next value.

It may be next()invoked function and continue to return the next value of an object called an iterator: Iterator.

May be used isinstance()is determined whether an object is Iteratoran object:

from collections import Iterator

        isinstance((x for x in range(10)), Iterator)

Generator Iterator objects are, but the list, dict, str though Iterable, not the Iterator.

The list, dict, str becomes like Iterable Iterator may be used ITER () function

summary

For those who can act on the loop are Iterable object type;

Who can act on the next () Iterator objects are a function of the type, which represents a sequence of lazy evaluation;

The aggregate data type list, dict, str, etc., but is not Iterable Iterator, but may () function is obtained by a Iter iter, Example: iter ([])

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_35577990/article/details/91320054