如何在Perl中向数组添加重复值?

时间:2022-06-02 08:51:10

I have an array @genotypes = "TT AG TT AG...." and want to add a spike to it (e.g. 20 x TT) to make a new array.

我有一个数组@genotypes =“TT AG TT AG ....”并希望添加一个尖峰(例如20 x TT)来制作一个新阵列。

I can obviously push "TT" into the array 20 times - but is there a simpler way of doing this? (ie. not @newarray = push @genotypes ("TT", "TT", "TT",......20 times!);

我显然可以将“TT”推入阵列20次 - 但有没有更简单的方法呢? (即不是@newarray =推@genotypes(“TT”,“TT”,“TT”,...... 20次!);

3 个解决方案

#1


35  

@newlist = (@genotypes, ('TT') x 20);

Yes, it is an x.

是的,它是一个x。

See Multiplicative Operators in perldoc perlop.

请参阅perldoc perlop中的乘法运算符。

#2


4  

The repetition operator is the most obvious way.
You could also use map:

重复算子是最明显的方式。你也可以使用map:

@newarray = (@genotypes, map 'TT', 1..20);

#3


3  

There's also the foreach way of pushing multiple identical values to an array:

还有将多个相同值推送到数组的foreach方法:

push @newarray, 'TT' foreach (1..20);

#1


35  

@newlist = (@genotypes, ('TT') x 20);

Yes, it is an x.

是的,它是一个x。

See Multiplicative Operators in perldoc perlop.

请参阅perldoc perlop中的乘法运算符。

#2


4  

The repetition operator is the most obvious way.
You could also use map:

重复算子是最明显的方式。你也可以使用map:

@newarray = (@genotypes, map 'TT', 1..20);

#3


3  

There's also the foreach way of pushing multiple identical values to an array:

还有将多个相同值推送到数组的foreach方法:

push @newarray, 'TT' foreach (1..20);