Python Learning note __12.7 itertools

Source: Internet
Author: User
Tags value of pi

# This is a learning note for the Liaoche teacher Python tutorial

1. Overview

Python's built-in module Itertools provides useful functions for manipulating iterative objects.

1.1. Several "infinite" iterators provided by Itertools

0) count ()

>>> Import Itertools

>>> natuals = itertools.count (1)

>>> for N in natuals:

... print (n)

count () creates an infinite iterator , so the code above prints out a sequence of natural numbers that cannot be stopped and can only be exited by pressing CTRL + C.

1) cycle ()

Cycle () repeats an infinite sequence of incoming sequences.

>>> Import Itertools

>>> cs = itertools.cycle (' ABC ') # Note that strings are also a type of sequence

>>> for C in CS:

.. print (c)

2) repeat ()

Repeat () is responsible for repeating an element indefinitely, but if you provide a second argument you can limit the number of repetitions

>>> ns = itertools.repeat (' A ', 3)

>>> for N in NS:

... print (n)

3) takewhile ()

A finite sequence can be intercepted on an infinite loop by a function such as takewhile () , based on a conditional judgment.

>>> natuals = itertools.count (1)

>>> ns = itertools.takewhile (lambda x:x <=, natuals)

>>> List (NS)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

1.2, Itertools several iterator action functions are provided

1) chain ()

Chain () can concatenate a set of iterative objects together to form a larger iterator

>>> for C in Itertools.chain (' ABC ', ' XYZ '):

.. print (c)

# Iteration Effect: ' A ' B ' ' C ' X ' Y ' Z '

2) groupby ()

GroupBy () picks up the repeating elements that are adjacent to the iterator and puts them together:

>>> for key, group in itertools.groupby (' aaabbbccaaa '):

.. print (Key, List (group))

...

A [' A ', ' a ', ' a ']

b [' B ', ' B ', ' B ']

c [' C ', ' C ']

A [' A ', ' a ', ' a ']

The selection rule is done by function, as long as the value returned by the two elements acting on the function is equal, the two elements are considered to be in a group, and the function returns the value as the key of the group.

>>> for key, group in itertools.groupby (' aaabbbccaaa ', Lambda C:c.upper ()): # Ignore Case

.. print (Key, List (group))

...

A [' A ', ' a ', ' a ']

b [' B ', ' B ', ' B ']

c [' C ', ' C ']

A [' A ', ' a ', ' a ']

Note: The Itertools module provides all the functions that deal with the iteration function, whose return value is not a list, but a iterator that is only really calculated when the For loop iteration is used.

2. Examples

The calculation of Pi can be based on the formula:

Using the Itertools module provided by Python, we calculate the first n items of this sequence and:

#-*-Coding:utf-8-*-

Import Itertools

Method One:

def Pi (N):  

N=itertools.count (ON) # Remove odd sequence, starting with 1, step 2

Ns=itertools.takewhile (lambda x:x<=2*n,n) #取出前N个数

num=list (NS) serialization of #将Iterator

Sum=0

For N in Num: # loop, if judgment value

If n%4==1:

n=4/n

Else

n=-4/n

Sum+=n

return sum

Method Two (netizens write):

def Pi (N):

' Calculate the value of pi '

# step 1: Create an odd sequence: 1, 3, 5, 7, 9, ...

List1 = Itertools.count (1, 2)

# step 2: Take the first N entries of the sequence: 1, 3, 5, 7, 9, ..., 2*n-1.

List2 = List (Itertools.takewhile (lambda x:x < 2 * N, List1))

# Step 3: Add positive and negative symbols and 4 divide: 4/1, -4/3, 4/5, -4/7, 4/9, ...

LIST3 = [4/(-i) for I in List2[1::2]] + [4/i for i in List2[::2]]

# Step 4: Summation:

return sum (LIST3) #这里求和得用sum () function, the SUM function adds all the values in the List3


Python Learning note __12.7 itertools

Related Article

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.