Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Equivalent to Ruby's #each_cons?

Is there a Pythonic equivalent to Ruby's #each_cons?

In Ruby you can do this:

array = [1,2,3,4]
array.each_cons(2).to_a
=> [[1,2],[2,3],[3,4]]
like image 379
maxhawkins Avatar asked May 04 '11 04:05

maxhawkins


People also ask

Is Python better than Ruby?

Python is generally better for educational use or for people who want to build quick programs rather than work as developers, while Ruby is better for commercial web applications. There are more specific differences when comparing Ruby versus Python, and they have in common that there are many ways to learn both.

Does Ruby replace Python?

Machine Learning On the other end, there is Ruby. While there is potential, Ruby must tweak its machine learning and AI libraries to do as well as Python in this field. Ruby won't replace Python anytime soon. TLDR: Python is a long-standing resource for machine learning programming.

Is Python or Ruby easier to learn?

Learning Curve Without a doubt, Python is much easier to learn because of how the language is structured - and how explicit it is. One can literally become proficient in two to three months. Ruby takes much longer to learn due to its flexibility.

Can I use Ruby and Python together?

Ruby and Python are two highly sought-after programming languages. They share many similarities and both are powerful options that solve specific problems. But few people know that Ruby and Python can be brought together to create efficient apps with capabilities for heavy calculations and handling Big Data.


1 Answers

I don't think there is one, I looked through the built-in module itertools, which is where I would expect it to be. You can simply create one though:

def each_cons(xs, n):
    return [xs[i:i+n] for i in range(len(xs)-n+1)]
like image 156
Gustav Larsson Avatar answered Sep 22 '22 22:09

Gustav Larsson