【问题标题】:How do I output the index of elements in an array that are also in another?如何输出另一个数组中的元素的索引?
【发布时间】:2014-01-21 17:27:32
【问题描述】:

我有两个数组:

A = ["a","s","p","e","n"]
V = ["a","e","i","o","u"]

我想输出一个数组,它显示数组A 中每个元素的索引,这也是V 中任何位置的元素。

换句话说:

some_function(A, V) == [0,3]

这是因为A[0]="a"A[3]="e" 匹配数组V 中的元素"a""e"。我怎么做?

【问题讨论】:

    标签: ruby arrays indexing match


    【解决方案1】:

    @Arup 已经回答了您的问题,我想我可能会详细说明一下。 Arup 建议您这样做:

    A.each_index.select{|i| V.include? A[i]}
    

    在哪里

    A = ["a","s","p","e","n"]
    V = ["a","e","i","o","u"]
    

    首先,A.each_index 是什么?在 IRB 中试一试:

    e = A.each_index # =>  #<Enumerator: ["a", "s", "p", "e", "n"]:each_index>
    e.class          # => Enumerator
    e.to_a           # => [0, 1, 2, 3, 4]
    

    所以枚举器e 是方法Enumerable#select 的接收者,Enumerable 是一个混合模块,包含在几个Ruby 类中,包括Enumerator。要检查吗?

    e.respond_to?(:select) # => true
    e.respond_to?(:map)    # => true
    e.respond_to?(:reduce) # => true
    

    接下来,请注意A.each_index 不依赖于A 的内容,只依赖于它的大小,因此我们可以将其替换为从0 迭代到A.size - 1 的任何枚举器,例如:

    m = A.size
    m.times.select{|i| V.include? A[i]}         # => [0, 3]
    0.upto(m-1).select{|i| V.include? A[i]}     # => [0, 3]
    

    我们可以确认这些是 Enumerator 对象:

    m.times.class      # => Enumerator
    0.upto(m-1).class  # => Enumerator
    

    include Enumerable 的其他主要类是 ArrayHashSetRangeIO(但是,从 Ruby 1.9 开始,不是 String),所以我们也可以这样做:

    Array(0...m).select{|i| V.include? A[i]}    # => [0, 3]
    (0...m).select{|i| V.include? A[i]}         # => [0, 3]
    require 'set'
    Set.new(0..m-1).select{|i| V.include? A[i]} # => [0, 3]
    

    请注意,无论接收者的类别如何,select 都会返回一个数组。大多数(但不是全部)返回集合的可枚举方法返回一个数组,而不管接收者的类是什么。

    【讨论】:

      【解决方案2】:

      如果 V 是一组数据(顺序无关紧要,没有重复),并且它很大,那么您可以通过将其转换为 Set 来获得性能优势,以便 include? 运行得更快,因为 Set 是建立在哈希上并获得 O(1) 检索时间:

      require 'set'
      A = ["a","s","p","e","n"]
      V = Set.new ["a","e","i","o","u"]
      A.each_index.select{|i| V.include? A[i]} # => [0, 3]
      

      【讨论】:

      • 或者只是把它变成一个哈希而不关心对的值是什么,这基本上就是 Set 所做的。
      【解决方案3】:

      我会这样做:

      A = ["a","s","p","e","n"]
      V = ["a","e","i","o","u"]
      A.each_index.select{|i| V.include? A[i]} # => [0, 3]
      

      【讨论】:

        猜你喜欢
        • 2021-11-24
        • 1970-01-01
        • 2013-07-19
        • 1970-01-01
        • 2018-12-24
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        • 2021-08-27
        相关资源
        最近更新 更多