gpt4 book ai didi

ruby - 如何按索引对数组元素进行分组?

转载 作者:行者123 更新时间:2023-12-03 20:25:50 26 4
gpt4 key购买 nike

我有数组 arr我想按数组 idx 中给出的索引分组.我的意思是,

  • 子数组 1 将在索引 1 处结束
  • 子数组 2 将在索引 5 处结束
  • 子数组 3 将在索引 7 处结束
  • 子数组 N 将从索引 8 处的元素到最后一个元素形成
    arr

  • 使用我当前的代码,我可以将第一个子数组的第一个索引为 idx idx[0] = 1。

    然后,如何复制数组中的所有索引 idx ?提前致谢。

    我当前的代码和输出是这样的:
    idx = [1,5,7]
    arr = ['a','b','c','d','e','f','g','h','i','j','k']

    arr.group_by.with_index { |z, i| i <= idx[0] }.values
    => [["a", "b"], ["c", "d", "e", "f", "g", "h", "i", "j", "k"]]

    我想要的输出是这样的:
    output   --> [["a", "b"], ["c", "d", "e", "f"], ["g", "h"], ["i", "j", "k"]]

    #Indexes --> 0 1 2 3 4 5 6 7 8 9 10

    最佳答案

    您可以使用 slice_after 在索引位于 idx 的每个项目之后对数组进行切片:

    idx = [1, 5, 7]
    arr = %w[a b c d e f g h i j k]

    arr.enum_for(:slice_after).with_index { |_, i| idx.include?(i) }.to_a
    #=> [["a", "b"], ["c", "d", "e", "f"], ["g", "h"], ["i", "j", "k"]]

    那个 enum_for (不幸的是)需要链接 slice_afterwith_index .

    关于ruby - 如何按索引对数组元素进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61403383/

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