Python implementation iterator (iterator) method example, pythoniterator
Overview
An iterator is a way to access collection elements. The iterator object is accessed from the first element of the set until all elements are accessed. The iterator can only move forward without moving back.
Lazy evaluation)
The iterator does not require you to prepare all elements in the entire iteration process in advance. This element is calculated only when it is iterated to an element. Before or after this, the element may not exist or be destroyed. This feature makes it especially suitable for Traversing large or infinite sets.
Today, an entity class is created, which is roughly as follows:
Class Account (): def _ init _ (self, account_name, account_type, account_cost, return_amount = 0): self. account_name = account_name # account name self. account_type = account_type # Account type self. account_cost = account_cost # monthly settlement self. return_amount = return_amount # return amount
Create an Object List:
Accounts = [Account ("Zhang San", "yearly user", 450.00, 50), Account ("Li Si", "Monthly user", 100.00 ), account ("Yang does not regret", "Monthly end user", 190.00, 25), Account ("Let our bank", "Monthly end user", 70.00, 10 ), account ("Ling Weifeng", "yearly user", 400.00, 40)]
I want to executenext()
Function, that is, click "next" when necessary to obtain the next element in the List.
Test it directly:
The List is not supported.next()
Features. At this time, List is only an iterable, not an iterator.
The differences between iterable and iterator are as follows:
- Iterable -- only implement the _ iter _ object;
- Iterator -- implements both the _ iter _ and _ next _ methods.
Where,__iter__
Returns the iterator object,__next__
Returns the next element of the iteration process.
1. Make the list iterator
To make the previous accounts List an iterator, you only neediter()
Function:
accounts_iterator = iter(accounts)(next(accounts_iterator)).account_name
The result is shown in:
It is estimated that many Python developers do not know such a simple function?
2. Custom iterator object
How to define your own iterator objects? In fact, according to the above definition__iter__
And__next__
Method.
Next we will define an AccountIterator class:
Class AccountIterator (): def _ init _ (self, accounts): self. accounts = accounts # account set self. index = 0 def _ iter _ (self): return self def _ next _ (self): if self. index> = len (self. accounts): raise StopIteration ("to the beginning... ") else: self. index + = 1 return self. accounts [self. index-1]
The running result is as follows:
After a while, the next () function is implemented. Python has many unexpected functions and is still waiting for us to explore. Maybe this is the charm and geeks of Python.
Summary
The above is all about this article. I hope this article will help you learn or use python. If you have any questions, please leave a message.