3. Advanced Features 3.1 slices
L = List (range (100))
L[0:3], starting at index 0, until index 3, but excluding index 3
If the first index is 0, you can also omit L[:3]
also supports taking the reciprocal element l[-2:] Take the reciprocal 2-bit element of the L set
L[10:20] Take the first 11-20 number:
L[:10:2] Take the first 10 numbers, one for every two
L[::5] All numbers, fetch 1 per five
' ABCDEFG ' [: 3]
Python does not have an intercept function for a string, it can be done simply by slicing one operation, very simple
3.2 iterations
In Python, you can iterate whether an iteration object has subscript or not
So how can you tell if an object is iterative? From collections Import iterable
Isinstance (' abc ', iterable);
In Java, the subscript can be iterated, and Python can use the enumerate function to iterate over the index and the element's
For I, value in enumerate ([' A ', ' B ', ' C '):
.. print (i, value)
3.3 List generation is a very simple and powerful built-in Python build that can be used to create lists.
L = []
>>> for x in range (1, 11):
... L.append (x * x) #使用循环
#使用列表生成式
[X*x for X in range (1,11) if x%2 = = 0] #要生成的元素x *x Place Front
#使用2层循环, create a full array
[M+n for M in ' ABC ' for n in ' XYZ ']
Import OS # Imports OS module, the concept of module
>>> [D for D in Os.listdir ('. ')] # Os.listdir can list files and directories
#for循环其实可以同时使用两个甚至多个变量, such as Dict's items (), can iterate both key and value at the same time:
D = {' X ': ' A ', ' y ': ' B ', ' z ': ' C '}
>>> for K, V in D.items ():
... print (k, ' = ', V)
#列表生成式也可以使用两个变量来生成list:
D = {' X ': ' A ', ' y ': ' B ', ' z ': ' C '}
>>> [k + ' = ' + V for K, V in D.items ()]
[' Y=b ', ' x=a ', ' z=c ']
#list中所有的字符串变成小写:
L = [' Hello ', ' World ', ' Apple ', None]
>>> [S.lower () for S in L if Isinstance (s,str) = = True]
3.4 Generators
The space of the list is limited, and in Python, one side loops the computation mechanism generator
g = (x * x for x in range (10))
For N in G:
Print (n)
#著名的斐波拉契数列 (Fibonacci), except for the first and second numbers, any number can be added by the first two numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
def fib (max):
N, a, b = 0, 0, 1
While n < max:
Print (b)
A, B = B, A + b
n = n + 1
Return ' Done '
#上面的函数和generator仅一步之遥. To turn the FIB function into a generator, simply change print (b) to yield B:
#generator函数 in the execution process, encountered yield is interrupted, the next time continue to execute.
# #杨辉三角
def triangles ():
L = [1] #定义一个list [1]
While True:
Yield L
L = [L[i] + l[i + 1] for I in range (len (L)-1)]
L.insert (0,1)
L.append (1)
if (Len (L) >10):
Break
#生成一个generator对象 and then iterate through the for loop to output each row
A=triangles (10)
For I in A:
Print (i)
3.5 iterators
There are several types of data that are directly acting on a For loop:
A class is a collection of data types, such as list, tuple, dict, set, str, and so on;
A class is generator, including generators and generator function with yield.
Iterable these objects that can directly act on a for loop are called an iterative object: Iterable.
You can use Isinstance () to determine whether an object is a Iterable object:
Isinstance ({}, iterable) #True
An object that Iterator can be called by the next () function and constantly returns the next value is called an iterator: Iterator
You can use Isinstance () to determine whether an object is a iterator object:
Isinstance ((x for X in range), Iterator) #True
Isinstance (' abc ', Iterator) #False
-------------------------------------------------------------
Because the Python iterator object represents a data stream, the iterator object can be called by the next () function and is returned continuously
The next data is thrown stopiteration error until there is no data. This data stream can be viewed as an ordered sequence,
But we can not know in advance the length of the sequence, can only continue to use the next () function to calculate the next data on demand,
So the calculation of iterator is inert and it is calculated only when it is necessary to return the next data.
-------------------------------------------
Collection data types such as list, Dict, str, and so on are iterable but not iterator, but a iterator object can be obtained through the ITER () function.
Advanced features of Python