Iteration:
An iterative object (iterable) that can directly act on a For loop object, such as a LIST/TUPLE/DICT/SET/STR/etc collection data type that can directly act on a for loop
>>> spam={1: ' A ', 2: ' B ', 3: ' C '}>>> for x in spam: #默认情况下, dict iteration is Keyprint x123>>> for Value in Spam.values (): #values (): Iteration valueprint valueabcfor k,v in Spam.items (): #items (): Iteration key-value print K,v1 A2 B3 C
How can I tell if an object is an iterative object? The method is judged by the iterable type of the collections module:
>>> from collections import iterable #导入collection模块 >>> isinstance (' abc ', iterable) # Isinstance (): Determines whether an object is iterator object True >>> isinstance ([1,2,3],iterable) true>>> isinstance (123, iterable) False
Simplified iterations: List-generated
Remove a string from the list and convert it to lowercase
>>> L1 = [' Hello ', ' World ', ' mac ', none]l2 = [X.lower () for x in L1 if Isinstance (x,str)] #isinstance () : Determine if string >>> l2[' Hello ', ' world ', ' Apple '
The or loop can be followed by an if judgment so that we can filter out only the even squares:
>>> [x * x for x in range (1, one) if x% 2 = = 0][4, 16, 36, 64, 100]
Python iteration, List-generation