什么是 Python itertools 的 Ruby 等价物,尤其是。组合/排列/分组?

Posted

技术标签:

【中文标题】什么是 Python itertools 的 Ruby 等价物,尤其是。组合/排列/分组?【英文标题】:What are the Ruby equivalent of Python itertools, esp. combinations/permutations/groupby? 【发布时间】:2011-01-27 10:41:21 【问题描述】:

Python 的itertools 模块在使用生成器处理可迭代/迭代器方面提供了很多好处。例如,

permutations(range(3)) --> 012 021 102 120 201 210

combinations('ABCD', 2) --> AB AC AD BC BD CD

[list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D

Ruby 中的等价物是什么?

相当于,我的意思是快速和高效的内存(Python 的 itertools 模块是用 C 编写的)。

【问题讨论】:

【参考方案1】:

Array#permutationArray#combinationEnumerable#group_by 从 1.8.7 开始在 ruby​​ 中定义。如果您使用的是 1.8.6,则可以从 facets 或 active_support 或 backports 获得等效方法。

示例用法:

[0,1,2].permutation.to_a
#=> [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]

[0,1,2,3].combination(2).to_a
#=> [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]

[0,0,0,1,1,2].group_by |x| x.map |k,v| v
#=> [[0, 0, 0], [1, 1], [2]]

[0,1,2,3].group_by |x| x%2
#=> 0=>[0, 2], 1=>[1, 3]

【讨论】:

以上是关于什么是 Python itertools 的 Ruby 等价物,尤其是。组合/排列/分组?的主要内容,如果未能解决你的问题,请参考以下文章

关于python的itertools模块

在 Python 中,为啥 itertools.cycle 需要额外的内存? [复制]

Itertools循环方法 - 为什么“while”循环?

python itertools 用法

python itertools 模块

python值itertools模块