learning to use iterators

Vito De Tullio vito.detullio at gmail.com
Wed Dec 24 10:12:01 EST 2014


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)))


-- 
By ZeD




More information about the Python-list mailing list