【问题标题】:What are the Ruby equivalent of Python itertools, esp. combinations/permutations/groupby?什么是 Python itertools 的 Ruby 等价物,尤其是。组合/排列/分组?
【发布时间】: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 编写的)。

【问题讨论】:

    标签: ruby combinations group-by permutation itertools


    【解决方案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]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-14
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 2011-05-05
      • 2010-11-13
      相关资源
      最近更新 更多