【问题标题】:Manipulating arrays: Inserting new element to a certain index and shifting other elements操作数组:将新元素插入到某个索引并移动其他元素
【发布时间】:2014-10-25 09:40:28
【问题描述】:

我有一个数组说

my @array = (1,4,5,8);

上述数组的每个元素可能有也可能没有子元素。

假设 1 有 2,3 作为孩子,5 有 10 作为孩子。

我必须操作数组使其变为1,2,3,4,5,10,8


我现在在做什么

foreach (@$children_indexes){ #myarray
        foreach ($self->{RELATION}[$_]->{CHILDREN}){ #find the child of each index
            push @$children_indexes, @$_; #I need to change this, as this is pushing at the end
        }
}

【问题讨论】:

    标签: arrays perl splice


    【解决方案1】:

    也许只使用map 代替:

    use strict;
    use warnings;
    
    my @array = ( 1, 4, 5, 8 );
    
    my %children = (
        1 => [ 2, 3 ],
        5 => [ 10 ],
    );
    
    my @new_array = map { ($_, @{ $children{$_} // [] }) } @array;
    
    print "@new_array\n";
    

    输出:

    1 2 3 4 5 10 8
    

    【讨论】:

      【解决方案2】:

      我猜$self->{RELATION}[$_]->{CHILDREN} 是一个数组引用?

      按索引或向后循环遍历您的索引数组:

      for my $index_index ( reverse 0..$#$children_indexes ) {
          if ( $self->{RELATION}[$children_indexes->[$index_index]]{CHILDREN} ) {
              splice @$children_indexes, $index_index+1, 0, @{ $self->{RELATION}[$children_indexes->[$index_index]]{CHILDREN} };
          }
      }
      

      或使用地图:

      my @array_with_children = map { $_, @{ $self->{RELATION}[$_]{CHILDREN} || [] } } @$children_indexes;
      

      (都假设 ...->{CHILDREN} 将不存在,或者如果没有孩子,无论如何都是错误的)

      【讨论】:

      • 当我这样使用它的时候。 pastebin.com/raw.php?i=bvPfmkbd 我收到错误消息:不能使用未定义的值作为数组引用。我已将代码放入已检查已定义的 IF 块中。
      【解决方案3】:

      不明白他为什么要使用 map 这可以用数组完美地完成。

      有了这个,你可以在你的循环中获取当前元素的索引,看看你在哪里添加:

      my @array = qw(A B C E F G);
      my $search = "C";
      
      my %index;
      @index{@array} = (0..$#array); 
      my $index = $index{$search}; < - getting the index of the curr element
      print $index, "\n";
      
      my @out_array;
      my $insert = 'D'; 
      
      push @out_array,
              @array[0..$index],
              $insert,
              @array[$index+1..$#array];
      
      print @array;
      print "\n";
      print @out_array;
      

      这是一个如何做到这一点的工作示例:)。

      【讨论】:

      • 确实如此。但是因为他要求数组并且唯一的答案是“使用地图”.. :D 我虽然最好举个例子来做其他事情(虽然它更复杂)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      • 2022-12-22
      • 1970-01-01
      • 2012-07-23
      • 2021-12-04
      • 1970-01-01
      相关资源
      最近更新 更多