什么是Ruby的等效Python的itertools的,ESP。组合/置换/ GROUPBY?
-
19-09-2019 - |
题
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)。
解决方案
Array#permutation
,Array#combination
和Enumerable#group_by
在红宝石自1.8.7定义。如果您在使用1.8.6你可以从面或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]}
不隶属于 StackOverflow