1-Slice operation
>>>l['AAA','BBB','CCC','DDD']>>> L[0:3]['AAA','BBB','CCC']>>> L[::5][0,5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]0-100 of all numbers, every 5 take one
View Code
2 iterative operations You can iterate as long as you have an iterative object
1>>> d = {'a': 1,'b': 2,'C': 3}2>>> forKeyinchD:3...PrintKey4 ...5 a6 C7BView Code
Iterate the default iteration key for a dictionary if you want to iterate over a value, you can use the following code
1>>>D2{'a': 1,'C': 3,'b': 2}3>>> forValuesinchd.itervalues ():4...PrintValues5 ...617382View Code
d.itervalues () an iterative object that returns a dictionary value
iterate keys and values at the same time:
1 for inch D.iteritems (): 2 ... Print K, v 3 ... 4 a 15 c 36 B 2
View Code
2.1 Judging an Iterative object
1 from Import iterable 2 >>> isinstance (D.iteritems (), iterable)3 True
View Code
The
2.3 Enumerate function can turn a list into an index-element pair so that both the index and the element itself can be iterated in the For loop
1 >>> for i, v in Enumerate ([ a , " b , ' c '
View Code
2.4 List-generated
1 for in range (1, one)]2 [1, 4, 9, +,,, +, +, Bayi, +]3 The X*X elements that need to be generated are placed in front
View Code
3 GeneratorsThe
process of generating a list is based on the calculation formula, and the edge is calculated as the edge is generated instead of one generation at a time
3.1 To change a list-generated [] to (), create a generator
1 for in range (ten)]2 >>> L3 [0, 1, 4, 9, +,- C8>4 list generation vs. generator comparison 5 for in range (ten))6 >> > g7 <generator object <genexpr> at 0x7f87935774b0>
View Code
The next () method of the generator makes it easy to generate subsequent elements, all printing requires a For loop variable
1>>>G.next ()2 03>>>G.next ()415>>>G.next ()647>>>G.next ()899>>> forNinchg:Ten...PrintN One ... A16 -25 -36 the49 -64 -81
View Code
3.2 The generator function can also be used with yield
generate a generator function by yield as follows
1 def fib (max): 2 ... N, a, b = 0, 0, 13 ... while (N < max): 4 ... yield b 5 ... A, B = A, a + b6 ... n = n + 17... 8 >>> fib (6)9 <generator object fib at 0x7f8793577aa0>
View CodeThe generator
function executes differently from the normal function, and each time the generator function is generated, it executes at the last yield .The
code example is as follows:
1>>>defOdd ():2...Print 'Step 1'3...yield14...Print 'Step 2'5...yield26...Print 'Step 3'7...yield38 ...9>>> o =Odd ()Ten>>>O.next () OneStep 1 A1 ->>>O.next () -Step 2 the2 ->>>O.next () -Step 3 -3
View Code
python-Slicing Iteration Builder