Catalog
What is iteration
Iterable & Iterrator
Dictionary iteration
Iteration of string
Judging iteratible objects ?
enumerate function
for Two variables in the loop
If given a list or tuple, We can go through for Loop through this list or tuple, This kind of traversal is called iteration (Iteration).
stay Python in , Iteration is through for ... in To complete , And many languages like Java Language , iteration list It's done by subscribing , such as Java Code :
for (i=0; i<list.length; i++) {
n = list[i];
}
It can be seen that ,Python Of for Loop abstraction is higher than Java Of for loop , because Python Of for Circulation can be used not only in list or tuple On , It can also act on other iteratable objects .
Can act directly on for Circular objects are collectively called iteratable objects (Iterable). Can be next() The object that function calls and returns the next value continuously is called an iterator (Iterator). be-all Iterable You can use built-in functions iter() To change into Iterator. For iterators , There is one __next() That's enough .
In your use for and in When the sentence is , The program will automatically call the iterator object of the object to be processed , And then use its next__() Method , Until a StopIteration abnormal .
list Although this data type has subscripts , But many other data types don't have subscripts , however , As long as it's an iterable object , With or without subscripts , You can iterate , such as dict You can iterate :
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
...
because dict The storage of is not according to list In order , therefore , The sequence of iterations is likely to be different . By default ,dict Iteratively key. If you want to iterate value, It can be used for value in d.values():,
If you want to iterate at the same time key and value, It can be used for k, v in d.items().
Because strings are also iteratable objects , therefore , It can also act on for loop :
for ch in 'ABC':
print(ch)
The result is :A B C
therefore , When we use for loop , As long as it works on an iterative object ,for The cycle can run normally , And we don't care much about what the object is list Or other data types .
that , How to judge whether an object is an iterative object ? The way is through collections Modular Iterable Type judgment :
from collections import Iterable
isinstance('abc', Iterable) # str Whether it can be iterated
The result is :True
isinstance([1,2,3], Iterable) # list Whether it can be iterated
The result is :True
isinstance(123, Iterable) # Whether integers can be iterated
The result is :False
If you want to list The implementation is similar to Java What about a subscript loop like that ?Python Built in enumerate Function can put a list Become index - Element pair , So you can do it for The loop iterates both the index and the element itself :
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
The result is :0 A 1 B 2 C
above for In circulation , Two variables are referenced at the same time ,
stay Python It's very common in , Consider the following code :
for x, y in [(1, 1), (2, 4), (3, 9)]:
print(x, y)
The result is :1 1 2 4 3 9