Python itertools module

Source: Internet
Author: User

Python built-in modules itertoolsProvides a very useful function for manipulating an iterative object

First, let's itertools look at a few "infinite" iterators provided:

Import itertools>>> natuals = itertools.count (1) for in natuals:      ... Print (n) ... 123 ...

Because count() an infinite iterator will be created, the above code will print out a sequence of natural numbers that cannot be stopped and can only be Ctrl+C pressed to exit.

cycle()Repeats the incoming sequence indefinitely:

>>>ImportItertools>>> cs = itertools.cycle ('ABC')#Note that a string is also a sequence of>>> forCinchCS: ...Print(c) ...'A''B''C''A''B''C'...

Also can't stop.

repeat()It is the responsibility to repeat an element indefinitely, but if you provide a second argument you can limit the number of repetitions:

>>> ns = itertools.repeat ('A', ten) for in NS: ...      Print (n) ... Print 10 times 'A'

An infinite sequence is for iterated indefinitely only at iteration, and if only an iterative object is created, it does not generate an infinite number of elements beforehand, and in fact it is not possible to create infinitely many elements in memory.

Infinite sequences can be iterated indefinitely, but usually we takewhile() intercept a finite sequence by the conditional judgment of the equal function:

>>> natuals = itertools.count (1)>>> ns = itertools.takewhile (lambda x:x <= 10 , Natuals)  for inch ns:      ... Print N. ... Print out 1 to ten

itertoolsSeveral iterator manipulation functions are provided that are more useful:

chain ()

chain()You can concatenate a set of iterative objects together to form a larger iterator:

 for  in Itertools.chain ('ABC''XYZ'):     Print (c) # iteration Effect: ' A ' B ' ' C ' ' X ' Y ' Z ' abcxyz
 from Import Chainitems_sorte=sorted (Chain (Questions,homework_record), reverse=true,key=Lambda  # merges two queryset into a single list, sorted by time

GroupBy ()

groupby()Pick up the repeating elements that are adjacent to the iterator and put them together:

>>> forKey, groupinchItertools.groupby ('aaabbbccaaa'):...     PrintKey, List (group)#Why do you use the list () function here? ... A ['A','A','A']b ['B','B','B']c ['C','C']a ['A','A','A']

The selection rule is actually 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. If we want to ignore the case grouping, we can let ‘A‘ the element and ‘a‘ both return the same key:

>>> forKey, groupinchItertools.groupby ('aaabbbccaaa',LambdaC:c.upper ()): ... .Printkey, List (group) ... A ['A','a','a']b ['B','B','b']c ['C','C']a ['A','A','a']
Summary

itertoolsThe module provides all the functions that deal with iterative functions, and their return values are not list, but are Iterator only for really calculated when the loop iteration is used.

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.