Description of the Itertools module in python---01

Source: Internet
Author: User

The Itertools module contains a number of functions that ultimately generate one or more iterators, which are described below:

In order to be able to use the functions in Itertools, you need to import the module:

>>>from Itertools Import *

Count (start=0,step=1):

The source code is:

def count (start=0,step=1): N=start while True:yield n n+=step

As you can see from the source code, the Count function produces a generator that can return a number by default, starting at 0 and increasing by 1 each time. For example:

>>>a=count (2,3) >>>a.next () 2>>>a.next () 5>>>a.next (8)

Of course, start and step can also be decimals. If the sys.maxint is exceeded, the counter overflows, and the-sys.maxint-1 begins to calculate.

Cycle (iterable):

The source code is:

def cycle (iterable): saved=[] for element in Iterable:yield element Saved.append (element) while Tr ue:for element in Saved:yield element

As you can see from the source code, the cycle function creates a list and then stores the elements in the iterable, and finally returns the elements in the list indefinitely. Therefore, the function of the cycle function is to create a generator that returns the elements in an infinite number of parameters, for example:

>>>a=cycle ([1,2,3,4]) >>>a.next () 1>>>a.next () 2>>>a.next () 3>>> A.next () 4>>>a.next () 1

Repeat (Object[,times]):

The source code is as follows:

def repeat (object,times=none): If Times is none:while True:yield object else:for i in XR Ange (Times): Yield object

When the Times is not specified, repeat infinitely repeats, returning the original object. When the Times is specified, the object is returned in a repeated time. For example:

>>>a=repeat (' abc ', 2) >>>a.next () ' ABC ' >>>a.next () ' ABC ' >>>a.next () Stopiteration exception


Description of the Itertools module in python---01

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.