如何合并两个数组,每个数组交替值,在Perl [英] How to merge two arrays, alternating values from each array, in perl

查看:293
本文介绍了如何合并两个数组,每个数组交替值,在Perl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有2个数组像下面提到

  @ A1 [维奈,拉吉,哈里]
@ B1 [花花公子,摇滚];

合并我想有这样的结果之后

  [
    维奈
    花花公子
    维奈
    岩
    拉吉
    花花公子
    拉吉
    岩
    掠夺
    花花公子
    掠夺
    岩
]

基本上我想ARRAY1的各项指标值合并数组2 2的各项指标值

添加到上面的问题,我有另一个查询

喜上面如何合并在特定的数组索引2阵列,例如我有2个阵列每160元的同样的问题,现在我想在台每5元合并阵列,是可能的... <? / p>

谢谢,
维奈


解决方案

下面是做到这一点的方法之一。可能不是最好的perl的语法,虽然。循环双意味着你将两个阵列的每个组合推到合并数组。我试着将它设置,使结果的顺序您在指定的问题。

 我@merged;我的一个$(@ A1){
  我的$ B(@ B1){
    推(@merged,($ A,$ B));
  }
}

suppose i have 2 arrays like mentioned below

@a1["Vinay", Raj, harry];
@b1["dude","rock"];

After merging i want to have result like this

[
    Vinay
    dude
    Vinay
    rock
    Raj
    dude
    Raj
    rock
    harry
    dude
    harry
    rock
]

basically i want to merge the each index values of array1 to all the index values of array2 2

Adding to the above question i have another query

hi for the same question above how to merge 2 arrays at particular array index, for example i have 2 arrays of each 160 elements , now i want to merge array at every 5th element in sets, is that possible..?

Thanks, Vinay

解决方案

Here is one way to do it. May not be the best perl syntax, though. The double for loop means you will be pushing every combination of the two arrays into the merged array. I've tried to set it up so that the result is in the order you specified in the question.

my @merged;

for my $a ( @a1 ) {
  for my $b ( @b1 ) {
    push( @merged, ($a, $b) );
  }
}

这篇关于如何合并两个数组,每个数组交替值,在Perl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆