什么是Python itertools的Ruby等价物,尤其是.组合/置换/ GROUPBY?

Hai*_*inh 13 ruby combinations group-by permutation python-itertools

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
Run Code Online (Sandbox Code Playgroud)

Ruby中的等价物是什么?

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

sep*_*p2k 18

Array#permutation,Array#combinationEnumerable#group_by在红宝石自1.8.7定义.如果您使用的是1.8.6,则可以从facet或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]}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,group_by与itertools.groupby的工作方式完全不同.[0,0,1,1,0,0] .group_by给出2组,而itertools.groupby给出3组 (4认同)