SlideShare una empresa de Scribd logo
1 de 21
THE PYTHON STD LIB BY
EXAMPLE – ALGORITHM
John
Saturday, December 21, 2013
Brief introduction
• Python includes several modules which can
implement algorithm elegantly and concisely.
• It support uprely procedural, OOP and
functional styles.
• It includes: functools, partial , itertools,
operator, contextlib etc
FUNCTOOLS –TOOLS FOR MANIPULATING
FUNCTIONS
Partial Objects: provide default
argument
• The partial objects can provide or change the default
value of the argument.
• Example code (assume we have define function
myfunc(a,b=1) :
>>> import functools
>>> p1 = functools.partial(myfunc,b=4)
>>> p1(‘passing a’)
>>> p2 = functools.partial(myfunc,’default a’,b=99)
>>> p2()
>>> p2(b=‘override b’)
Function update_wrapper()
• The partial object does not have __name__
and __doc__ attributes by default.
• Using update_wrapper(0 copies or added
attributes from the original function.
Format:
>>> functools.update_wrapper(p1,myfunc)
the “rich comparison”
First let us learn which is “rich comparion” in
python.
•Rich comparison method API (__lt__, __le__,
__eq__, __gt__, __ge__)
(Here le means less than, le means “less or equal”,
gt means “greater than”, ge means “greater than
or equal”)
•These method API can help perform a single
comparison operation and return a Boolean value
Example of rich comparision
We implement __eq__ and __gt__.
Functools.total_ordering can implement other
operator (<, <=, >= etc) base on eq and gt.
Function cmp_to_key: convert
cmp to key for sorting
• In Python 2.xx, cmp do comparion:
cmp(2,1) -> 1
cmp(1,1) -> 0
cmp(1,2) -> -1
• In python 3, cmp in sort function no longer
supported.
• Functools.cmp_to_key convert cmp to key
for sorting
Quick example of cmp_to_key
• Built-in funtion cmp need two argument.
• Sorted function can use other option
key=func. Sorted by key (only support this on
Python 3.X)
ITERTOOLSITERATOR
FUNCTIONS
Brief introduction
• The itertools module includes a set of
functions for working with sequence data
sets (list, tuple,set,dict etc).
• Iterator based code offer better memory
comsumption.
Function chain(): Merge iterators
• Take serveral iterators as arguments and
return a single iterator
Function imap: similar as map
• Imap accept a function, and multiple
sequences, return a tuple.
Other function merge and split
iterators
• Function izip: like zip, but combine iterator
and return iterator of tuple instead of list
• Function islice: similar as slice
• Function imap: similar as map
• Function ifilter: similar as filter, filter those
items test functions return True
• Function ifilterfalse: filter those items where
the test function return False
Function starmap:
• First, let us review the star * syntax in Python.
• Star * means unpack the sequence reference as
argument list.
>>> def foo(bar,lee):
print bar,lee
>>> a = [1,2]
>>> foo(a) # it is wrong, need two arguments
>>> foo(*a) # it is right. The list is unpack
>>>foo(1,2) # it is the same thing
Function starmap: unpack the
input
• Unpack the item as argument using the *
syntax
Function count(): iterator produce
consecutive integers
• Function count(start=0,step=1): user can pass
the start and step value.No upper bound
argument.
>>> a = itertools.count(start=10,step=10)
>>> for i in a:
print I
if I >100:
break

Print list 10,20,30 … 110
Function cycle: iterator do
indefinitely repeats
• It need remember the whole input, so it may
consume quite a bit memo if input iterator is
long.
Function repeat: repeat same
value several time
• This example mean repeat ‘a’ 5 times.
>>> itertools.repeat(‘a’, 5)
It is similar as list [‘a’,’a’.’a’,’a’,’a’]
The return is a iterator but not list. So it use the
memo only when it is called.
Function dropwhile and takewhile
• Func dropwhile start output while condition
become false for the first time
• Example, 3rd element do not met x<1. So it
return 3 to end of this list
Function dropwhile and takewhile
• The opposite of dropwhile: stop output while
condition become false for the first time
• So all output items meet the condition
function.

Más contenido relacionado

La actualidad más candente (20)

Java Arrays and DateTime Functions
Java Arrays and DateTime FunctionsJava Arrays and DateTime Functions
Java Arrays and DateTime Functions
 
List
ListList
List
 
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
 
Stack Data structure
Stack Data structureStack Data structure
Stack Data structure
 
An Introduction to the C++ Standard Library
An Introduction to the C++ Standard LibraryAn Introduction to the C++ Standard Library
An Introduction to the C++ Standard Library
 
List in java
List in javaList in java
List in java
 
Algorithms: II
Algorithms: IIAlgorithms: II
Algorithms: II
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Understanding the components of standard template library
Understanding the components of standard template libraryUnderstanding the components of standard template library
Understanding the components of standard template library
 
Queues
QueuesQueues
Queues
 
Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Functions with heap and stack
 
Grid search (parameter tuning)
Grid search (parameter tuning)Grid search (parameter tuning)
Grid search (parameter tuning)
 
Ppt presentation of queues
Ppt presentation of queuesPpt presentation of queues
Ppt presentation of queues
 
Stacks
StacksStacks
Stacks
 
Python - Lecture 12
Python - Lecture 12Python - Lecture 12
Python - Lecture 12
 
Data Analysis packages
Data Analysis packagesData Analysis packages
Data Analysis packages
 
Iterators and Generators
Iterators and GeneratorsIterators and Generators
Iterators and Generators
 
Python standard data types
Python standard data typesPython standard data types
Python standard data types
 
Lists
ListsLists
Lists
 

Similar a Python advanced 3.the python std lib by example – algorithm

Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional ProgrammingFrancesco Bruni
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programsGeethaPanneer
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxleavatin
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in pythonSarfaraz Ghanta
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptxYagna15
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default argumentsNikhil Pandit
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in SwiftSaugat Gautam
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingestorebackupr
 
python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptxMONAR11
 
L 5 Numpy final ppt kirti.pptx
L 5 Numpy final ppt kirti.pptxL 5 Numpy final ppt kirti.pptx
L 5 Numpy final ppt kirti.pptxKirti Verma
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceKrithikaTM
 

Similar a Python advanced 3.the python std lib by example – algorithm (20)

Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Advance python
Advance pythonAdvance python
Advance python
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Function
FunctionFunction
Function
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
 
Python functions
Python functionsPython functions
Python functions
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programming
 
python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptx
 
L 5 Numpy final ppt kirti.pptx
L 5 Numpy final ppt kirti.pptxL 5 Numpy final ppt kirti.pptx
L 5 Numpy final ppt kirti.pptx
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
 
10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 

Más de John(Qiang) Zhang

A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)John(Qiang) Zhang
 
Python advanced 3.the python std lib by example – system related modules
Python advanced 3.the python std lib by example – system related modulesPython advanced 3.the python std lib by example – system related modules
Python advanced 3.the python std lib by example – system related modulesJohn(Qiang) Zhang
 
Python advanced 2. regular expression in python
Python advanced 2. regular expression in pythonPython advanced 2. regular expression in python
Python advanced 2. regular expression in pythonJohn(Qiang) Zhang
 

Más de John(Qiang) Zhang (8)

Git and github introduction
Git and github introductionGit and github introduction
Git and github introduction
 
Python testing
Python  testingPython  testing
Python testing
 
Profiling in python
Profiling in pythonProfiling in python
Profiling in python
 
Introduction to jython
Introduction to jythonIntroduction to jython
Introduction to jython
 
Introduction to cython
Introduction to cythonIntroduction to cython
Introduction to cython
 
A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)
 
Python advanced 3.the python std lib by example – system related modules
Python advanced 3.the python std lib by example – system related modulesPython advanced 3.the python std lib by example – system related modules
Python advanced 3.the python std lib by example – system related modules
 
Python advanced 2. regular expression in python
Python advanced 2. regular expression in pythonPython advanced 2. regular expression in python
Python advanced 2. regular expression in python
 

Último

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 

Último (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

Python advanced 3.the python std lib by example – algorithm

  • 1. THE PYTHON STD LIB BY EXAMPLE – ALGORITHM John Saturday, December 21, 2013
  • 2. Brief introduction • Python includes several modules which can implement algorithm elegantly and concisely. • It support uprely procedural, OOP and functional styles. • It includes: functools, partial , itertools, operator, contextlib etc
  • 3. FUNCTOOLS –TOOLS FOR MANIPULATING FUNCTIONS
  • 4. Partial Objects: provide default argument • The partial objects can provide or change the default value of the argument. • Example code (assume we have define function myfunc(a,b=1) : >>> import functools >>> p1 = functools.partial(myfunc,b=4) >>> p1(‘passing a’) >>> p2 = functools.partial(myfunc,’default a’,b=99) >>> p2() >>> p2(b=‘override b’)
  • 5. Function update_wrapper() • The partial object does not have __name__ and __doc__ attributes by default. • Using update_wrapper(0 copies or added attributes from the original function. Format: >>> functools.update_wrapper(p1,myfunc)
  • 6. the “rich comparison” First let us learn which is “rich comparion” in python. •Rich comparison method API (__lt__, __le__, __eq__, __gt__, __ge__) (Here le means less than, le means “less or equal”, gt means “greater than”, ge means “greater than or equal”) •These method API can help perform a single comparison operation and return a Boolean value
  • 7. Example of rich comparision We implement __eq__ and __gt__. Functools.total_ordering can implement other operator (<, <=, >= etc) base on eq and gt.
  • 8. Function cmp_to_key: convert cmp to key for sorting • In Python 2.xx, cmp do comparion: cmp(2,1) -> 1 cmp(1,1) -> 0 cmp(1,2) -> -1 • In python 3, cmp in sort function no longer supported. • Functools.cmp_to_key convert cmp to key for sorting
  • 9. Quick example of cmp_to_key • Built-in funtion cmp need two argument. • Sorted function can use other option key=func. Sorted by key (only support this on Python 3.X)
  • 11. Brief introduction • The itertools module includes a set of functions for working with sequence data sets (list, tuple,set,dict etc). • Iterator based code offer better memory comsumption.
  • 12. Function chain(): Merge iterators • Take serveral iterators as arguments and return a single iterator
  • 13. Function imap: similar as map • Imap accept a function, and multiple sequences, return a tuple.
  • 14. Other function merge and split iterators • Function izip: like zip, but combine iterator and return iterator of tuple instead of list • Function islice: similar as slice • Function imap: similar as map • Function ifilter: similar as filter, filter those items test functions return True • Function ifilterfalse: filter those items where the test function return False
  • 15. Function starmap: • First, let us review the star * syntax in Python. • Star * means unpack the sequence reference as argument list. >>> def foo(bar,lee): print bar,lee >>> a = [1,2] >>> foo(a) # it is wrong, need two arguments >>> foo(*a) # it is right. The list is unpack >>>foo(1,2) # it is the same thing
  • 16. Function starmap: unpack the input • Unpack the item as argument using the * syntax
  • 17. Function count(): iterator produce consecutive integers • Function count(start=0,step=1): user can pass the start and step value.No upper bound argument. >>> a = itertools.count(start=10,step=10) >>> for i in a: print I if I >100: break Print list 10,20,30 … 110
  • 18. Function cycle: iterator do indefinitely repeats • It need remember the whole input, so it may consume quite a bit memo if input iterator is long.
  • 19. Function repeat: repeat same value several time • This example mean repeat ‘a’ 5 times. >>> itertools.repeat(‘a’, 5) It is similar as list [‘a’,’a’.’a’,’a’,’a’] The return is a iterator but not list. So it use the memo only when it is called.
  • 20. Function dropwhile and takewhile • Func dropwhile start output while condition become false for the first time • Example, 3rd element do not met x<1. So it return 3 to end of this list
  • 21. Function dropwhile and takewhile • The opposite of dropwhile: stop output while condition become false for the first time • So all output items meet the condition function.