所以我有这个(排序很好的)数组.
有时我需要数组中的所有元素.但有时我需要所有偶数索引的成员和所有奇数索引的成员在一起.然后,有时我需要将它分成三组,其中一组中有0,3,6等指数,然后是下一组中的1,4,7,最后是2,5,8.
这可以通过group_by索引的模数来完成.你自己看:
https://play.crystal-lang.org/#/r/4kzj
arr = ['a', 'b', 'c', 'd', 'e']
puts arr.group_by { |x| arr.index(x).not_nil! % 1 } # {0 => ['a', 'b', 'c', 'd', 'e']}
puts arr.group_by { |x| arr.index(x).not_nil! % 2 } # {0 => ['a', 'c', 'e'], 1 => ['b', 'd']}
puts arr.group_by { |x| arr.index(x).not_nil! % 3 } # {0 => ['a', 'd'], 1 => ['b', 'e'], 2 => ['c']}
Run Code Online (Sandbox Code Playgroud)
但not_nil!那里的感觉就像一个代码嗅觉/警告,有更好的方法.
我可以获取元素的索引而无需查找并处理Nil类型吗?
你也可以这样做:
arr = ['a', 'b', 'c', 'd', 'e']
i = 0
puts arr.group_by { |x| i += 1; i % 1 }
i = 0
puts arr.group_by { |x| i += 1; i % 2 }
i = 0
puts arr.group_by { |x| i += 1; i % 3 }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |