Python 相当于 Ruby 的 #each_cons?
是否有与 Ruby 的 #each_cons
等效的 Pythonic?
在 Ruby 中你可以这样做:
array = [1,2,3,4]
array.each_cons(2).to_a
=> [[1,2],[2,3],[3,4]]
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]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
Python 肯定可以做到这一点。如果你不想这么急切,可以使用 itertool 的 islice 和 izip。另外,重要的是要记住,普通切片将创建一个副本,因此如果内存使用很重要,您还应该考虑 itertool 等效项。
each_cons = lambda l: zip(l[:-1], l[1:])
Python can surely do this. If you don't want to do it so eagerly, use itertool's islice and izip. Also, its important to remember that normal slices will create a copy so if memory usage is important you should also consider the itertool equivalents.
each_cons = lambda l: zip(l[:-1], l[1:])
更新:不要介意我下面的答案,只需使用
toolz.itertoolz.sliding_window()
——它会做正确的事情。对于一个真正的惰性实现,当序列/生成器长度不足时,保留 Ruby 的
each_cons
的行为:示例:
请注意,izip 参数上使用的元组解包应用于大小为
n
是itertools.tee(xs, n)
的结果(即“窗口大小”),而不是我们想要迭代的序列。UPDATE: Nevermind my answer below, just use
toolz.itertoolz.sliding_window()
-- it will do the right thing.For a truly lazy implementation that preserves the behavior of Ruby's
each_cons
when the sequence/generator has insufficient length:Examples:
Note that the tuple unpacking used on the arguments for izip is applied to a tuple of size
n
resulting ofitertools.tee(xs, n)
(that is, the "window size"), and not the sequence we want to iterate.接近@Blender的解决方案,但有修复:
或者
Close to @Blender's solution but with a fix:
Or
Elias 代码的 Python 3 版本
Python 3 version of Elias's code
这是使用
collections.deque
的实现。这也支持任意生成器用法:
Here's an implementation using
collections.deque
. This supports arbitrary generators as wellUsage:
我认为没有,我查看了内置模块
itertools
,这正是我所期望的。您可以简单地创建一个: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:对于这样的事情,itertools 是您应该查看的模块:
然后:
对于更通用的解决方案,请考虑:
这允许任意长度的子序列和任意重叠。用法:
For such things,
itertools
is the module you should be looking at:Then:
For an even more general solution, consider this:
This allows arbitrary lengths of subsequences and arbitrary overlapping. Usage:
我的列表解决方案(Python2):
编辑: 使用 Python 3
itertools.izip
不再存在,因此您使用普通的zip
:My solution for lists (Python2):
Edit: With Python 3
itertools.izip
is no longer, so you use plainzip
:快速一句:
A quick one-liner: