【问题标题】:How to group array elements by index?如何按索引对数组元素进行分组?
【发布时间】:2020-08-07 17:34:21
【问题描述】:

我有数组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  

【问题讨论】:

    标签: ruby group-by slice


    【解决方案1】:

    您可以使用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 新手)更紧凑的解决方案
    • 这是一个变体:i = -1; arr.slice_after { idx.include?(i += 1) }.to_a.
    【解决方案2】:

    另一种解决方案

    idx = [1, 5, 7]
    arr = ['a','b','c','d','e','f','g','h','i','j','k']
    from = 0
    
    arr.map.with_index { |a, i|  
      if idx.include?(i)
        result = arr[from..i]  
        from = i + 1 
      end
      result
    }.compact
    
     => [["a", "b"], ["c", "d", "e", "f"], ["g", "h"]] 
    

    【讨论】:

      【解决方案3】:
      arr = [9, 3, 1, 6, 2, 4, 0, 1, 5, 8] 
      end_idx = [1, 5, 7]
      

      [-1, *end_idx, arr.size-1].uniq.each_cons(2).
        map { |s,e| arr.values_at(s+1..e) }
        #=> [[9, 3], [1, 6, 2, 4], [0, 1], [5, 8]]  
      

      步骤如下:

      a = [-1, *end_idx, arr.size-1]
        #=> [-1, 1, 5, 7, 9]
      b = a.uniq
        #=> [-1, 1, 5, 9]
      c = b.each_cons(2)
        #=> #<Enumerator: [-1, 1, 5, 7, 9]:each_cons(2)> 
      c.map { |s,e| arr.values_at(s+1..e) }
        #=> [[9, 3], [1, 6, 2, 4], [0, 1], [5, 8]] 
      

      通过将c 转换为数组,可以看到枚举器c 生成并传递给map 的元素。

      c.to_a
        #=> [[-1, 1], [1, 5], [5, 7], [7, 9]] 
      

      Array#values_at

      【讨论】:

      • 感谢您的帮助。它似乎有效,我看到的唯一问题是,如果 end_idx=[1,5,9] 一个空数组 [] 保留在输出数组的末尾。
      • Ger,很好的收获。我做了一个小改动(添加了uniq),解决了这个问题并将[-1, *[1, 5, 5, 9], arr.size-1] 转换为[-1, 1, 5, 9]
      猜你喜欢
      • 2020-07-03
      • 2023-01-31
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 2017-06-06
      • 2020-02-24
      • 1970-01-01
      相关资源
      最近更新 更多