代码之家  ›  专栏  ›  技术社区  ›  Geo

当我遍历数组时,如何也获得元素的索引?

  •  8
  • Geo  · 技术社区  · 15 年前

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

    我想抓住所有包含 o . 我要这个:

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

    但是我要做什么才能同时接收一个索引,或者能够访问中的索引呢 grep

    3 回复  |  直到 15 年前
        1
  •  17
  •   mob    15 年前

    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
  •  13
  •   Ether    15 年前

    看一看 List::MoreUtils

    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;
    
        3
  •  2
  •   toolic    15 年前

    这将用所需内容填充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   , $_;
        }
    }