Itertools is one of the most interesting python libraries. It contains a series of functions inspired by functional languages that are used to work with iterators.
In this article I will mention some of the ones that have caught my attention the most and that are worth keeping in mind so as not to reinvent the wheel every time.
Several times I have implemented an infinite count (well, it ends
explicitly at some point with a break) using a while True loop. itertools offers us a better alternative:
from itertools import count for i in count(start=2, step=2): if i > 10: break print(i)
2 4 6 8 10
As can be seen in the example, if it were not for the break, count would return infinite numbers. The above code is roughly equivalent to:
i = 2 while True: if i > 10: break print(i) i = 2
2 4 6 8 10
A function to do something very common: get data from a stream in batches of size n. Let's look at an example:
from itertools import batched sequence = [1, 2, 3, 4, 5, 6, 7] for batch in batched(sequence, 2): # lotes de tamaño 2 print(batch)
(1, 2) (3, 4) (5, 6) (7,)
It should be noted that the last batch may be of a size less than or equal to n, as in this case. Quite useful, don't you think?
Another simple and useful function. Given a sequence (actually, given an iterator), it gives us its elements in pairs.
Let's see it better with an example:
from itertools import pairwise sequence = [1, 2, 3, 4, 5, 6, 7] for a, b in pairwise(sequence): print(a, b)
1 2 2 3 3 4 4 5 5 6 6 7
The number of pairs is one less than the size of the input sequence.
Finally, for this short entry, I want to talk about product, a
implementation of the Cartesian product.
Useful to replace a nested for that loops through two data streams:
from itertools import product A = [1, 2, 3] B = [5, 6, 7] for a, b in product(A, B): print(a, b)
1 5 1 6 1 7 2 5 2 6 2 7 3 5 3 6 3 7
Receives a parameter that allows us to make the Cartesian product of a
sequence with itself:
from itertools import product A = [1, 2, 3] for a1, a2, a3 in product(A, repeat=3): print(a1, a2, a3)
1 1 1 1 1 2 1 1 3 1 2 1 1 2 2 1 2 3 1 3 1 1 3 2 1 3 3 2 1 1 2 1 2 2 1 3 2 2 1 2 2 2 2 2 3 2 3 1 2 3 2 2 3 3 3 1 1 3 1 2 3 1 3 3 2 1 3 2 2 3 2 3 3 3 1 3 3 2 3 3 3
In a future post, I will mention other functions of this useful module
python standard library. I hope it is useful to you.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3