-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
329268d
commit b4e1274
Showing
3 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
# slicing generators | ||
|
||
Ever wondered how to slice a #Python generator? | ||
|
||
You can use `itertools.islice()`: | ||
|
||
``` | ||
>>> def gen(): | ||
... yield from range(1, 11) | ||
... | ||
>>> g = gen() | ||
>>> g[:2] | ||
Traceback (most recent call last): | ||
File "<stdin>", line 1, in <module> | ||
TypeError: 'generator' object is not subscriptable | ||
>>> from itertools import islice | ||
>>> my_slice = islice(g, 2) | ||
>>> my_slice | ||
<itertools.islice object at 0x7fb2ab084540> | ||
>>> list(my_slice) | ||
[1, 2] | ||
>>> [i for i in g] | ||
[3, 4, 5, 6, 7, 8, 9, 10] | ||
# another example of generator exhaustion: | ||
>>> g = gen() | ||
>>> ', '.join(str(i) for i in g) | ||
'1, 2, 3, 4, 5, 6, 7, 8, 9, 10' | ||
>>> ', '.join(str(i) for i in g) | ||
'' | ||
``` | ||
|
||
#generators |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
# merge PDF files | ||
|
||
TIL how to merge PDF files in Python -> the `pypdf` library makes this really easy: | ||
|
||
``` | ||
from itertools import islice | ||
from pathlib import Path | ||
from pypdf import PdfWriter | ||
with PdfWriter() as merger: | ||
files = (Path.home() / "code" / "articles" / "outputs").glob('*.pdf') | ||
for file in islice(files, 3): | ||
merger.append(file) | ||
merger.write("output.pdf") | ||
``` | ||
|
||
Source project where I found this: https://github.com/ahmedlemine/pdf-merger | ||
|
||
|