Python,itertools Module

Source: Internet
Author: User

Use of the Itertools module:

#Coding=utf-8"""Itertools Module"""ImportItertoolsImportUnitTestclassTestitertools (unittest. TestCase):defTest_count (self):"""Itertools.count () infinite generation of natural numbers"""natuals= Itertools.count (1, 1) Res=0 forRinchnatuals:ifr = = 10: Res=R BreakSelf.assertequal (10, Res)deftest_cycle (self):"""itertools.cycle () value inside the infinite repeating sequence"""my_list="ABC"result= []         forNum, resinchEnumerate (itertools.cycle (my_list)): Result.append (res)ifnum = = 5:                 Breakself.assertequal (['A','B','C','A','B','C'], result)deftest_repeat (self):"""itertools.repeat (' A ', 3) repeat A 3 times"""result= [Res forResinchItertools.repeat ('ABC', 3)] Self.assertequal (['ABC','ABC','ABC'], result)defTest_takewhile (self):"""Itertools.takewhile () intercepts a finite sequence"""natuals=itertools.count (0) result= Itertools.takewhile (LambdaX:x <= 5, Natuals) self.assertequal ([0,1, 2, 3, 4, 5], List (result))defTest_chain (self):"""Itertools.chain () composes two iterations of objects into an iterative object"""Iter1= ['A','B'] Iter2='CCC'result=Itertools.chain (Iter1, Iter2) self.assertequal (['A','B','C','C','C'], List (result))defTest_groupby (self):"""GroupBy () picks up the repeating elements adjacent to the iterator and puts them together ."""text="aaaaaaccccddddmmm"result= {Key:list (val) forKey, Valinchitertools.groupby (Text)} self.assertequal (['M','M','M'], result['M'])if __name__=='__main__': Unittest.main ()

Python,itertools Module

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.