Python's method of traversing iterable objects

Python's method of traversing iterable objects

iterable

Iteration (traversal) is to visit each item in the object one by one in a certain order.
There are many objects in Python that can be directly traversed through the for statement, such as list, string, dict, etc. These objects are iterable and are called iterable objects.
An iterable object can be thought of as a container in which a finite number of elements are stored, and each element can be retrieved from it. Then this container is iterable, and this container is an iterable object.
All iterable objects need to implement the __iter__ method, which is used to convert iterable objects into iterators when we loop.

iterator

Iterators are a subset of iterable objects. It is an object that can remember the position of the traversal. The difference between it and iterable objects such as lists, tuples, collections, and strings lies in the implementation of the __next__() method. That is, through this method, elements can be taken out one by one. That is, the method of traversing an iterable object is an iterator.
Iterators support __iter__() and __next__() methods. Among them: The iter () method returns the iterator object itself, and this method of the iterable object returns its iterator.
The next () method returns the next element of the container, raising a StopIteration exception at the end.

Method 1: Use a for loop to traverse a simple structure

Direct for loop traversal of iterable objects

li=[1,2,3,4]
li2=[5,6,7,8]
for i in li2:
    li.append(i)
print(li)
[1, 2, 3, 4, 5, 6, 7, 8]

Method 2: Borrowing the range() and len() functions to traverse

This method can use the commonly used alist[i] in the array to traverse the list

li=[1,2,3,4]
li2=[5,6,7,8]
for i in range(len(li2)):
    li.append(li2[i])
print(li)
[1, 2, 3, 4, 5, 6, 7, 8]

Method 3: Borrow iter() function to traverse

This method uses the idea of ​​an iterator, an iterator is an object that can remember the position of the traversal, and the iterator has two basic methods: iter() and next().
Use iter(iterable) to convert an iterable object into an iterator; use next(iterator) to get the next value of the iterator

li3 = [5,6,7,8]
for i in iter(li3):
    print(i)
5
6
7
8

Method 4: Borrow the enumerate() function to traverse

When you need to traverse both the index and the elements, you can consider using the enumerate function. The enumerate function accepts a traversable object, such as a list, a string, etc.

li4 = ['C','C#','JAVA']
for i,li4 in enumerate(li4):
    print(i+1,li4)
1 C
2 C#
3 JAVA

Guess you like

Origin blog.csdn.net/weixin_57038791/article/details/129224380