Python basic syntax iteration

Iteration

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

Python basic syntax iteration
Python basic syntax (1)
Python3 basic syntax
Python basic syntax generator
Basic syntax of Python
Python basic syntax list production
Python basic syntax and number types
Python basic operators
Python basic drawing tutorial (1)
Python function basic learning
Basics of Python syntax
python_ crawler basic learning
Python basic data types
Basic knowledge of Python (1)
Python basic data types
Python basic knowledge question bank
Python basic drawing tutorial (two)
Python introductory notes [basic grammar (on)]
Python entry notes [basic grammar (below)]
Python file operation basic process analysis
Python crawler basic knowledge points finishing
Real zero basic Python development web
Basic analysis of Python turtle library implementation
Python basic actual combat-guess the age game