Skip to content

Instantly share code, notes, and snippets.

@dutc
Created December 1, 2021 14:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dutc/4e2cdf42469548094ed22090b6634571 to your computer and use it in GitHub Desktop.
Save dutc/4e2cdf42469548094ed22090b6634571 to your computer and use it in GitHub Desktop.
`nwise` and friends!
#!/usr/bin/env python3
from itertools import tee, islice, zip_longest, chain, repeat
nwise = lambda g, *, n=2: zip(*(islice(g, i, None) for i, g in enumerate(tee(g, n))))
nwise_longest = lambda g, *, n=2, fv=object(): zip_longest(*(islice(g, i, None) for i, g in enumerate(tee(g, n))), fillvalue=fv)
first = lambda g, *, n=1: zip(chain(repeat(True, n), repeat(False)), g)
last = lambda g, *, m=1, s=object(): ((xs[-1] is s, x) for x, *xs in nwise_longest(g, n=m+1, fv=s))
if __name__ == '__main__':
print(
f"{[*nwise('abcd')] = }",
f"{[*nwise_longest('abcd')] = }",
f"{[*first('abcd')] = }",
f"{[*last('abcd')] = }",
sep='\n',
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment