First, iteration
Through a for loop to iterate through a list, we call this traversal the same way as iteration . An iterative operation can be performed as long as an iterative object is available.
The following code can be used to determine whether an object is iterative.
A class is a collection of data types, such as,,, list tuple , and dict set str so on;
One is generator , including the generator and yield the generator function with the band (which we'll cover in the next section)
from Import iterable>>> isinstance ("ABC", iterable) True>>> Isinstance ([],iterable] True>>> isinstance ({"name":" Nadech"},iterable) True
Iterates through the contents of the list in an iterative way.
names = ["nadech","Aguilera","Sara" ] for in names: print(name)
If we want to add a sequence number to the index-element pair in front of the output name above, we can do so through the enumerate function.
names = ["nadech","Aguilera","Sara" ] for in Enumerate (names): print(i,name)
#输出结果
0 Nadech
1 Aguilera
2 Sara
In the dictionary iteration , we can iterate over the key,value of the dictionary , or the key-value pair .
>>> d = {"name":"Nadech"," Age":" A","Address":"Nanjing"}>>> forKeyinchd: #迭代key值...Print(Key) ... addressnameage>>> forValueinchd.values (): #迭代value值 ...Print(value) ... Nanjingnadech22>>> forKey,valueinchD.items (): #迭代key-value to ...Print(key,value) ... address nanjingname nadechage22
Similarly, there are two variables in a for loop, such as:
for inch [(1, 1), (2, 4), (3, 9)]: ... Print (x, y) ... 1 12 43 9
Python note nine (iteration)