In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the Python programming itertools module to deal with iterable set related functions, the article is very detailed, has a certain reference value, interested friends must read it!
Containers and iterable objects
Add some basic concepts before the official start. There are containers and iterable objects in Python.
Container: a data structure used to store multiple elements, such as lists, tuples, dictionaries, collections, etc.
Iterable object: an object that implements the _ _ iter__ method is called an iterable object.
Iterators and generators are also derived from iterable objects:
Iterator: an object that implements both _ _ iter__, and _ _ next__ methods is called an iterator.
Generators: functions with the yield keyword are generators.
This makes it clear that the scope of iterable objects is larger than that of containers. And the iterable object can only be used once, and getting the value after using it will prompt the StopIteration exception.
In addition, iterable objects have some limitations:
You cannot use len functions on iterable objects
You can use the next method to deal with iterable objects, and the container can be converted into an iterator through the iter function
The for statement automatically calls the container's iter function, so the container can also be iterated through the loop.
Count () function
The count function is generally compared with the range function. For example, the range function needs to define the lower limit of the generation range, and the upper limit and step size are optional, while the count function specifies the lower limit and step size, and the upper limit does not need to be declared.
The function prototype is declared as follows
Count (start=0, step=1)-> count object
The test code is as follows, in which the decision condition to jump out of the loop must be added, otherwise the code will run all the time.
From itertools import counta = count (5,10) for i in a: print (I) if I > 100: break
In addition, the count function takes non-integer arguments, so what is defined in the following code is also correct.
From itertools import counta = count (0.5,0.1) for i in a: print (I) if I > 100: breakcycle function
You can loop through a set of values with the cycle function, and the test code is as follows:
From itertools import cyclex = cycle ('dream eraser abcdf') for i in range (5): print (next (x), end= ") print ("\ n ") print (" * "* 100) for i in range (5): print (next (x), end=")
The code output is as follows:
Dream of rubber eraser
*
A b c d f
You can see that the cycle function is very similar to the for loop.
Repeat function
The repeat function is used to return a value repeatedly. The official description of the function is as follows:
Class repeat (object): "" repeat (object [, times])-> create an iterator which returns the object for the specified number of times. If not specified, returns the object endlessly.
Do a simple test to see the results:
From itertools import repeatx = repeat ('Eraser') for i in range (5): print (next (x), end= ") print ("\ n ") print (" * "* 100) for i in range (5): print (next (x), end=")
No matter how you look at this function, it doesn't seem to be of much use.
Enumerate function, adding serial number
This function has been briefly introduced in the previous article, and it is in the _ _ builtins__ package, so it will not be explained too much.
The basic format is as follows:
Enumerate (sequence, [start=0])
Where the start parameter is the starting position of the subscript.
Accumulate function
This function returns an iterable object based on the given function. The default is the cumulative effect, that is, the second parameter is operator.add. The test code is as follows:
From itertools import accumulatedata = [1,2,3,4,5] # calculate the cumulative sum print (list (accumulate (data) # [1,3,6,10,15]
For the above code, modify it to accumulate.
From itertools import accumulateimport operatordata = [1,2,3,4,5] # calculate cumulative print (list (accumulate (data, operator.mul)
In addition, the second parameter can also be a function such as max,min, such as the following code:
From itertools import accumulatedata = [1,4,3,2,5] print (list (accumulate (data, max)
The code output is as follows, which actually compares any two values in data and leaves the maximum value.
[1, 4, 4, 4, 5]
Chain and groupby function
The chain function is used to combine multiple iterators into a single iterator, while groupby can divide one iterator into multiple sub-iterators.
First, show the application of the groupby function:
From itertools import groupbya = list (groupby ('rubber eraser')) print (a)
The output is as follows:
[('Oak')
('skin',)
('wipe',)]
In order to use the groupby function, it is recommended to sort the original list first, because it is a bit like slicing, and if you find something different, you will divide it into an iterator.
The chain function is used to concatenate multiple iterative objects as follows:
From itertools import groupby, chaina = list (chain ('ABC',' AAA', range (1) print (a) zip_longest and zip
The zip function has been explained in previous blogs, and the difference between zip_longest and zip is that the result returned by zip is the shortest sequence, while zip_longest is the longest.
The test code is as follows, you can compare the results by yourself.
From itertools import zip_longesta = list (zip ('ABC', range (5), [10,20,30,40]) print (a) a = list (zip_longest (' ABC', range (5), [10,20,30,40]) print (a)
If zip_logest encounters a sequence with inconsistent length, the missing part will be filled with None.
Tee function
The tee function can clone iteratable objects and produce multiple generators, each of which can output each element of the input.
From itertools import teea = list (tee ('eraser')) print (a) compress function
This function determines the trade-off of an element through the predicate (whether or not, True/False). The simplest code is as follows:
From itertools import compressa = list (compress ('Eraser', (0,1,1)) print (a) islice, dropwhile, takewhile, filterfalse, filter
Each of these functions takes a subset of the input iterable object and does not modify the element itself.
This section only lists the prototype declaration of each function, and the specific usage can be referred to directly.
Islice (iterable, stop)-- > islice objectislice (iterable, start, stop [, step])-- > islice objectdropwhile (predicate, iterable)-- > dropwhile objecttakewhile (predicate, iterable)-> takewhile objectfilterfalse (function or None, sequence)-- > filterfalse object
Only the parameters in filterfalse are the first function and the last sequence.
The test code is as follows, especially noticing that the first parameter is callable, the function.
From itertools import islice, dropwhile, takewhile, filterfalsea = list (filterfalse (lambda x: X in ["skin", "eraser"], "eraser") print (a) the above is all the content of the article "what are the functions of the Python programming itertools module dealing with iterable sets?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.