gpt4 book ai didi

crystal-lang - 有没有办法在 Crystal 中使用_index进行group_by?

转载 作者:行者123 更新时间:2023-12-03 01:24:00 24 4
gpt4 key购买 nike

所以我有这个(排序良好的)数组。

有时我需要数组中的所有元素。但其他时候,我需要将所有偶数索引成员放在一起,以及将所有奇数索引成员放在一起。再说一次,有时我需要将它分成三组,一组索引为 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']}

但是那里的 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 }

关于crystal-lang - 有没有办法在 Crystal 中使用_index进行group_by?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51474828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com