【问题标题】:How can I also get an element's index when I grep through an array?当我通过数组进行 grep 时,如何获取元素的索引?
【发布时间】:2011-03-02 06:44:48
【问题描述】:

假设我有这个列表:

my @list = qw(one two three four five);

我想获取所有包含o 的元素。我有这个:

my @containing_o = grep { /o/ } @list;

但是我还需要做什么才能接收索引,或者能够访问grep 正文中的索引?

【问题讨论】:

    标签: arrays perl grep


    【解决方案1】:

     

    my @index_containing_o = grep { $list[$_] =~ /o/ } 0..$#list;  # ==> (0,1,3)
    
    my %hash_of_containing_o = map { $list[$_]=~/o/?($list[$_]=>$_):() } 0..$#list
                # ==> ( 'one' => 0, 'two' => 1, 'four' => 3 )
    

    【讨论】:

      【解决方案2】:

      看看List::MoreUtils。你可以用数组做很多方便的事情,而不必滚动你自己的版本,而且它更快(因为它是在 C/XS 中实现的):

      use List::MoreUtils qw(first_index indexes);
      
      my $index_of_matching_element = first_index { /o/ } @list;
      

      对于所有匹配的索引,然后是它们对应的元素,你可以这样做:

      my @matching_indices = indexes { /o/ } @list;
      my @matching_values = @list[@matching_indices];
      

      或者只是:

      my @matching_values = grep { /o/ } @list;
      

      【讨论】:

      • 这不会只返回第一个元素的索引吗?
      • 是的。我认为 Ether 打算使用 indexes 函数,该函数将列出所有为该块返回 true 的索引。
      • 是的,我做到了...在检查我的工作之前我太早点击了提交。谢谢:)
      • +1 提到它的 C/XS 实现使其更快
      【解决方案3】:

      这会用你想要的填充 2 个数组,遍历输入数组一次:

      use strict;
      use warnings;
      my @list = qw(one two three four five);
      my @containing_o;
      my @indexes_o;
      for (0 .. $#list) {
          if ($list[$_] =~ /o/) {
              push @containing_o, $list[$_];
              push @indexes_o   , $_;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-14
        • 1970-01-01
        • 1970-01-01
        • 2013-12-03
        • 1970-01-01
        相关资源
        最近更新 更多