How to implement the # each_cons function similar to Ruby in Python
Most people do not understand the knowledge points of this article "how to achieve # each_cons function similar to Ruby in Python", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to achieve similar Ruby # each_cons function in Python" article.
You can do this in Ruby:
Array = [1Jing 2jue 3je 4] array.each_cons (2). To_a= > [1Jing 2], [2Jing 3], [3Jing 4]]
For this kind of content, the module you should look at is: itertools
From itertools import tee, izipdef pairwise (iterable): "s-> (s 0 ~ S 1), (s 1 ~ 2), (s 2, s 3),..." A, b = tee (iterable) next (b, None) return izip (a, b)
Then:
> list (pairwise ([1,2,3,4])) [(1,2), (2,3), (3,4)]
For a more generic solution, consider:
Def split_subsequences (iterable, length=2, overlap=0): it = iter (iterable) results = list (itertools.islice (it, length)) while len (results) = length: yield results results = results [length-overlap:] results.extend (itertools.islice (it, length-overlap)) if results: yield results
This allows for any length of suborder and arbitrary overlap. Usage:
> list (split_subsequences ([1,2,3,4], length=2)) [[1,2], [3,4]] > > list (split_subsequences ([1,2,3,4], length=2, overlap=1)) [[1,2], [2,3], [3,4], [4]
In this way, a similar effect can be achieved.
The above is about the content of this article on "how to achieve # each_cons function similar to Ruby in Python". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.