#the For loop of an iterative python can be used not only on a list or a tuple, but also on other objects that can iterate. #list This data type although there is subscript, but many other data types are not subscript, but as long as the object can be iterated, whether or not subscript, can iterate, such as dict can iterate:D = {'a': 1,'b': 2,'C': 3} forKeyinchD:Print(Key)#because Dict storage is not ordered in list order, the resulting order of the iterations is likely to be different. #by default, the Dict iteration is key. If you want to iterate over value, you can use for value in D.values (), if you want to iterate both key and value at the same time, you can use a for-K, V in D.items (). forValueinchd.values ():Print(value) forKvinchD.items ():Print(k, v)#because a string is also an iterative object, it can also be used for A For loop: forChinch 'ABC': Print(CH)#So, when we use a For loop, as long as it works on an iterative object, the for loop will work, and we don't care much about whether the object is a list or another data type. #So, how can you tell if an object is an iterative object? The method is judged by the iterable type of the collections module:#determines whether an object is an iterative object fromCollectionsImportIterablet= Isinstance ('ABC', iterable)#whether Str can iteratePrint(t) t= Isinstance ([1, 2, 3], iterable)#whether the list can iteratePrint(t) t= Isinstance (123, iterable)#whether integers can be iteratedPrint(t)#What if you want to implement subscript loops like Java for a list? Python's built-in 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: forI, ValueinchEnumerate (['A','B','C']): Print(i, value)#0 A#1 B#2 CPrint('--------------------------------')#The above for loop, which also references two variables, is common in python, such as the following code: forX, yinch[(1, 1), (2, 4), (3, 9)]: Print(x, y)
Iterations in Python