Bo Zhong Entertainment platform development and Python learning

Source: Internet
Author: User

objects, iterators, and generators that can be iterated
Iteration is the cornerstone of data processing. Scan memory for data sets that don't fit in, we're looking for an inert way to get data items, which is to get one data item at a time. This is the iterator pattern.

1 Iterative objects

1.1 Why the sequence can be iterated

When the interpreter needs to iterate over object x, it automatically calls ITER (x), and the built-in ITER function has the following effects:

Check to see if the object implements the Iter method and invoke it if it is implemented to get an iterator.

If the Iter method is not implemented, but the GetItem method is implemented, Python creates an iterator that attempts to get the element in order (starting at index 0)

If the attempt fails, Python throws a TypeError exception, usually prompting "C object is not Iterable", where c is the target iteration object

2 iterators

Interface for 2.1 iterators

The standard iterator interface has two methods:

Next: Returns the next available element, if there is no element, throws Stopiteration

iter: Returns self to use iterators where an iterator should be used, for example in a for loop

6.2.21 Classic Iterators

#可迭代对象和迭代器一定不能在一个对象中同时实现, for a typical iterator.
Import re
Import Reprlib
?
Re_word = Re.compile (' \w+ ')
?
Class sentence:

def __init__(self,text):    self.text = text    self.words = RE_WORD.findall(text)def __iter__(self):    return SentenceIterator(self.words)def __repr__(self):    return ‘Sentence(%s)‘ % reprlib.repr(self.text)

#实现迭代器
Class Sentenceiterator (Self,words):
def Init(self,words):
Self.words = words
Self.index = 0
def next(self):
Try
Word = Self.words[self.index]
Except Indexerror:
Raise Stopiteration ()
Self.index + = 1
return word
def iter(self):

Bo Zhong Entertainment platform development and Python learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.