The implementation has changed from sum to deque. Why deque?
python3
from collections import deque
n = 10000
%timeit sum(1 for _ in range(n)) # 2.5
%timeit deque(enumerate(range(n), 1), maxlen=1)[0][0] # 2.6
>>>
1000 loops, best of 3: 439 µs per loop
1000 loops, best of 3: 289 µs per loop
Indeed, it's getting faster.
Divide into the specified number so that they are approximately the same size.
python3
from more_itertools import divide, always_iterable, adjacent, groupby_transform, context
[tuple(i) for i in divide(3, range(10))]
>>>
[(0, 1, 2, 3), (4, 5, 6), (7, 8, 9)]
Iterable remains as it is, and non-iterable ones become iterable.
python3
always_iterable(None)
>>>
()
always_iterable(1)
>>>
(1,)
always_iterable([1,3,5])
>>>
[1, 3, 5]
Set True before and after where the conditions match.
python3
list(adjacent(lambda x: x==3, range(7)))
>>>
[(False, 0),
(False, 1),
(True, 2),
(True, 3),
(True, 4),
(False, 5),
(False, 6)]
list(adjacent(lambda x: x==3, range(7), distance=2)) #Up to 2 differences before and after
>>>
[(False, 0),
(True, 1),
(True, 2),
(True, 3),
(True, 4),
(True, 5),
(False, 6)]
Convert keys and values after grouping.
python3
[(i,list(j)) for i,j in groupby_transform([1,1,3,2,2,2],
lambda x: f'<{x}>', #Key conversion
lambda x: x*10)] #Value conversion
>>>
[('<1>', [10, 10]), ('<3>', [30]), ('<2>', [20, 20, 20])]
The one that can be used with with is a generator.
python3
with open(file name) as fp:
print(fp.read())
↓ You can write like this
print(*[fp.read() for fp in context(open(file name))])
Reference: Introduction of itertools and more-itertools
that's all
Recommended Posts