learning to use iterators
Rustom Mody
rustompmody at gmail.com
Wed Dec 24 15:34:05 EST 2014
On Wednesday, December 24, 2014 8:42:32 PM UTC+5:30, Vito De Tullio wrote:
> Seb wrote:
>
> >>>> def n_grams(a, n):
> > ... z = (islice(a, i, None) for i in range(n))
> > ... return zip(*z)
> > ...
> >
> > I'm impressed at how succinctly this islice helps to build a list of
> > tuples with indices for all the required windows.
>
> If you want it succinctly, there is this variation on the theme:
>
> n_grams = lambda a, n: zip(*(a[i:] for i in range(n)))
+3 but -1
+1 for using an inlining the z
+1 for showing that the * can take any expression [I did not know that]
+1 for the slice in succinct form
-1 for the lambda -- quite unnecessary and a red-herring
If squeezing out the last char is the idea
n_grams = lambda a, n: zip(*(a[i:] for i in range(n)))
is same as
def n_grams(a,n):return zip(*(a[i:]for i in range(n)))
More information about the Python-list
mailing list