for Cycle is Python Universal sequence iterator in : It can traverse the elements in any ordered sequence in one step .for Statement applies to strings , list , tuple , Other built-in

Iteratable objects and new objects created by classes .

for Usually than while Loops are easier to code and run more efficiently , When a sequence needs to be traversed , First consider for loop . generally speaking , When an object has a specific length

Degree hour , have access to for loop , Use when not in use while loop . for example : use for Loop through the files in the directory , Characters in file , Elements in the list, etc . nothing

On whether the length is known , All of these have their own specific length . But in the game , General use while loop , Because I don't know when the user will close the program .

The following code is for Basic format of loop , Inside is the content that needs to be executed circularly :
for target in sequence: print(target)
Python Running for Cycle time , The elements in the sequence object are assigned to the target one by one , And execute the loop body once . The loop body usually uses the assignment target to refer to the sequence

Current item for , It's like it's a cursor stepping in a sequence .

stay for The name used as the assignment target in is usually for Variables within the loop body , That is, local variables . It can be changed in the loop body , But when the control returns to the top of the cycle again

Ministry time , Automatically set as the next item in the sequence . After the cycle , This variable is usually the last accessed item , That is, the last item in the sequence , Unless cycle

with break Statement exit .

Here's an example , We put the names from left to right x Assigned to three elements in the list , Every execution print sentence . because print Function defaults to newline , therefore

Each element is a new line when printed . In the first iteration x=‘spam’, Second iteration x=‘eggs’, Third iteration x=‘ham’.
Python exchange of learning Q group :906715085 for x in ['spam', 'eggs', 'ham']: print(x)

Calculate the sum of elements in the sequence .
total = 0 for i in [1,2,3,4]: total = total + i print(total)
You can also traverse any data type , such as , We traverse a string , And leave a space between each letter to print it out .
word = 'hello' for letter in word: print(letter, end=' ')

<>for Loop assignment to tuple

When looping through a tuple sequence , The elements in the sequence can be assigned to the target tuple , The items of tuples in the sequence are successively assigned to the elements corresponding to the target tuple .
t = [(1,2), (3,4), (5,6)] for (a,b) in t: print(a,b)

<> Traversal dictionary
d = {'a':1, 'b':2, 'c':3} for key, value in d.items(): print(key, value)

<> Split after assignment
t = [(1,2), (3,4), (5,6)] for both in t: a,b = both print(a,b)
We don't have to be here for Corresponding assignment target in the loop , You can also split the assignment target in the loop body .

<> Nested loop

for Loops can also be nested , Use built-in range() Function returns a list , Generate numbers for each cycle 0-2. each i Inside the loop j
Cycle cycle . In the following example , Each cycle runs 3 second , Total 9 second .
for i in range(3): for j in range(3): print(i,j)

python Can be used in itertools The module gets the same result , Instead of two nested for loop
from itertools import product for pairs in product(range(3), range(3)): print(
here pairs Output as a tuple . Take another little chestnut with nested loops , such as , Extract all letters from a sentence .
sentence = 'This is a sentence.' for word in sentence.split(' '): for char in
word: print(char)
first floor for Split sentences into lists by spaces , That is, every word , The second level is to traverse each letter of each word , In this way, all letters excluding spaces are extracted .


Python Built in range The function is an iterator that generates a list of integers , It is usually associated with for Recycling combined use , Is an easy way to generate a list of numbers you need . As shown in the above example , By giving it parameters
3 To generate a list [0, 1, 2].
range(start, stop[, step])
This is range Basic grammar of ,start Is the initial value ,stop End value of , Note that the value of the final stop will not be equal to , No more than stop Value of ,step Is the value of each increment , Default is 1.

<> Basic Usage
for i in range(10): print(i)
generate 0-9 Sequence of .

<> particular range
for i in range(5,10): print(i)
generate 5-9 A sequence of .

<> Sequence of specific intervals
for i in range(5,10,2): print(i)
Generating sequence [5,7,9]

<> Reverse sequence
for i in range(10,0,-1): print(i)
step Can be negative , That is, every decline step, To generate a reduced sequence .
l = list(range(3)) print(l[::-1])

The above code can also get an inverse sequence , actually list[start:stop:step], It can also be regarded as a for Loop to use . Of course, it can also be used list(reversed(l)) Get an inverse sequence .

<> Explain one thing

Don't be for Use in circulation range(len(sequence)) To get the index of each element in the sequence , because Python Allows you to cycle the sequence directly . stay Python
in , When you use for Loop sequence , Most of the time, you don't need to know the index . The usage in the following example is not recommended . If you have to get , Enumeration can be used enumerate.
seq = ['spam', 'eggs', 'ham'] for i in range(len(seq)): print(f'{seq[i]} is at
<> enumeration

Enumerate Is a built-in generator object , It has a next Built in function call next method , This method returns one at a time through a loop (index, value)
tuple , We can for Tuple assignment is used in the loop to split these tuples .
for index, target in enumerate(['spam', 'eggs', 'ham']): print(f'{target} is
at index{index}')

Above example , Gets the index of the elements in the list .

use enumerate function , The index variable is incremented with the target sequence in the sequence ( Default from 0 start ). You can change the default start counter by using the start number as the second parameter .
for index, target in enumerate(['spam', 'eggs', 'ham'], 10): print(f'{target}
is at index{index}')

Can see , The starting index becomes 10, Then increase in order 1.

Change the sequence in the loop

Sometimes during the cycle , The sequence of loops needs to be modified .
l = ['spam', 'eggs', 'ham']for word in l: if 's' in word: l.remove(word) print(
The intuitive function of the above example is , Delete list with s New words , But the result is , Just deleted the first one with s of spam This word , Not deleted eggs.

We need to copy the reference of the list , Then cycle through and modify the original content . In this way , The actions in the loop can only be applied to the original list .
l = ['spam', 'eggs', 'ham']for word in l[:]: if 's' in word: l.remove(word)

<> Explain one thing

Pay attention here [:] A shallow copy is created for the reference of the list . You can also import replication modules to use copy.copy(sequence).

Nested lists actually require deep copies , Depends on what you want to delete . You need to import the replication module to execute copy.deepcopy(sequence). Delete while iterating over objects

object , Understand it and for Circular relationships are important , Because it may cause unexpected output , As for deep copy and shallow copy , That's another point of knowledge .


zip Allow us to use for Loop to access multiple sequences in parallel ,zip Takes one or more sequences as parameters and returns a series of tuples , These tuples combine the elements in these sequences

Line item pairing .
l1 = [1,2,3,4] l2 = [5,6,7,8] for x,y in zip(l1, l2): print(x, y, x + y)

use zip Created a list of tuple pairs , We're in a for There are two separate lists in the loop , of course , It is also not limited to two parameters , Just make sure you have the same

Number of targets to split a given list , Here we have two lists , So we just need x and y To unzip them .

When the parameter length is different ,zip The result tuple is truncated by the length of the shortest sequence .
s1 = 'abc' s2 = 'xyz123' for x,y in zip(s1, s2): print(x, y)

Can be used at runtime zip Build dictionary .
keys = ['spam', 'eggs', 'ham'] values = [1,3,5]d = {} for k,v in zip(keys,
values): d[k] = vprint(d)

keys = ['spam', 'eggs', 'ham'] values = [1,3,5] d = dict(zip(keys, values))

Traverse a sorted list .
abc = ['b','d','a','c','f','e'] for letter in sorted(abc): print(letter)

Or use sorted(abc) Get an ascending sequence , use sorted(abc, reverse=True) Get a descending sequence .

<> List combination

Any list combination can be converted to for loop , Otherwise, it won't work . The element is written directly in square brackets , Is a way to construct a new list . The speed of list combination is about

Manual for Twice the cycle , Because their iteration is in the interpreter C Speed of language execution . however , Making them too complex reduces readability .
for y in ['foo','bar']: for x in [y.lower(), y.upper()]: print(x)

use for Cycle compression .
l = [x for y in ['foo','bar'] for x in [y.lower(),y.upper()]] print(l)
<> Transformation process

the second for Put it first for behind , Then drop the first one for Colon of , Write a second one at the beginning for Variable for , Finally, put everything in parentheses .

for instance , Create a new list and put the string “ham” Enter as many times as in the original list .
Python exchange of learning Q group :906715085### lst = ['spam', 'ham', 'eggs', 'ham']ham_ lst = []for
itemin lst: if item == 'ham': ham_lst.append(item)print(ham_lst)
Use list combination .
lst = ['spam', 'ham', 'eggs', 'ham']ham_ lst = [item for item in lst if item ==
'ham'] print(ham_lst)
The above two pieces of code get the same result .


built-in map Function returns an iterator , This iterator calls the function on the value in the input iterator , And return the result . here , We create a function to call , It returns the value of a given number 2 times .
def times_two(x): return 2 * x
Now we will use map Loop this function , stay range This function is called on each number given by the function .
for i in map(times_two, range(5)): print(i)
perhaps , There are two ways , Get the same list , You can understand it as simple for loop .map All you do is call each result in the sequence times_two function ,Map
existence , Can not be used for loop .
list(map(times_two, range(5))) [times_two(num) for num in range(5)]
In the face of epidemic situation Don't panic

break: Jump out of the nearest closed loop

continue: Jump to the top of the nearest closed loop

pass: Don't do anything? , Empty statement placeholder

else: Operates when and only when the cycle exits normally

for The loop stops halfway through the iteration , Once implemented break sentence , this for The cycle will stop . for letter in 'Python': if letter
== 'o': break print(letter)


take break Replace with continue Time ,continue Statement stopped in this single iteration for loop , And continue to the next iteration ( That is, letters n).
for letter in 'Python': if letter == 'o': continue print(letter)


In the following example , When letter == ‘o’ There was no reaction at the time , It's like if
The condition never existed . It did , But nothing happened , It's more like a placeholder . If I knew there would be one if condition , I'll write it later , It just hasn't been put in yet if Content of condition .
for letter in 'Python': if letter == 'o': pass print(letter)


In the following example ,else Clause only in for Execute when the cycle ends normally .
#for Abnormal end for letter in 'Python': if letter == 'o': print('loop ended
prematurely') break print(letter) else: print('loop finished')#for Normal end for
letterin 'Python': if letter == 'x': break print(letter) else: print('loop

©2019-2020 Toolsou All rights reserved,
C++ of string of compare usage Python Study notes ( one )evo Tool usage problems ——Degenerate covariance rank, Umeyama alignment is not possibleRISC-V_GD32VF103-TIMER0 timer interrupt java Array subscript variable _Java Basic grammar : array be based on stm32 Control four-wheel trolley motor drive ( one ) be based on redis Design of liking function Software engineering career planning mysql Query random data by conditions _MySQL Random query of several qualified records centos7 install RabbitMq