If a list or tuple is given, we can traverse the list or tuple through a for loop. This traversal is called Iteration. Iteration can be understood as a loop in the C/Java language.
In Python, iteration is done through for… in, while in many languages such as C, iterating list is done through subscripts
for s in['A','B','C']: #Iteration(cycle)A list
print(s)>>>
A
B
C
Because the storage of dict is not arranged in the order of the list, the order of the results of the iteration is likely to be different.
d ={'a':1,'b':2,'c':3,}for key in d:print(key)>>> #Iterate only the key
a
c
b
By default, dict iterates over keys. If you want to iterate value, you can use for value in d.values(), if you want to iterate key and value at the same time, you can use for k, v in d.items().
So, how to judge an object is an iterable object? The method is to judge the Iterable type of the collections module:
from collections import Iterable
isinstance('abc', Iterable) #whether str is iterable
>>> True
isinstance([1,2,3], Iterable) #whether the list is iterable
>>> True
isinstance(123, Iterable) #Whether the integer is iterable
>>> False
What if you want to implement a subscript loop similar to C language for list? Python's built-in enumerate function can turn a list into an index-element pair, so that the index and the element itself can be iterated in a for loop at the same time:
for i, value inenumerate(['A','B','C']):print(i, value)>>>0 A
1 B
2 C
Recommended Posts