Python itertools 的 Ruby 等价物是什么,特别是。组合/排列/groupby?

发布于 2024-08-25 11:17:20 字数 407 浏览 3 评论 0原文

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 编写的)。

Python's itertools module provides a lots of goodies with respect to processing an iterable/iterator by use of generators. For example,

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

What are the equivalent in Ruby?

By equivalent, I mean fast and memory efficient (Python's itertools module is written in C).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寂寞美少年 2024-09-01 11:17:20

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]}

Array#permutation, Array#combination and Enumerable#group_by are defined in ruby since 1.8.7. If you're using 1.8.6 you can get equivalent methods from facets or active_support or backports.

Example Usage:

[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]}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文