是否有一个紧凑的 Perl 操作来切片数组中的替代元素? [英] Is there a compact Perl operation to slice alternate elements from an array?

查看:45
本文介绍了是否有一个紧凑的 Perl 操作来切片数组中的替代元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 Python 中有一个数组 myarray,我可以使用切片表示法

myarray[0::2]

只选择偶数索引的元素.例如:

<预><代码>>>>ar = [零"、一"、二"、三"、四"、五"、六"]>>>ar [ 0 : : 2 ]['零','二','四','六']

Perl 中是否有类似的工具?

谢谢.

解决方案

有数组切片:

我的@slice = @array[1,42,23,0];

有一种方法可以在 $x 和 $y 之间生成列表:

我的@list = $x .. $y

有一种方法可以从列表中构建新列表:

my @new = map { $_ * 2 } @list;

还有一种获取数组长度的方法:

我的 $len = $#array;

放在一起:

my @even_indexed_elements = @array[map { $_ * 2 } 0 .. int($#array/2)];

诚然,它不如 Python 等效,但它可以完成相同的工作,如果您经常使用它并希望避免一些写作,您当然可以将其放入子例程中.

>

还有很可能允许在 List::AllUtils 中以更自然的方式编写它.

If I have an array myarray in Python, I can use the slice notation

myarray[0::2]

to select only the even-indexed elements. For example:

>>> ar = [ "zero", "one", "two", "three", "four", "five", "six" ]
>>> ar [ 0 : : 2 ]
['zero', 'two', 'four', 'six']

Is there a similar facility in Perl?

Thanks.

解决方案

There's array slices:

my @slice = @array[1,42,23,0];

There's a way to to generate lists between $x and $y:

my @list = $x .. $y

There's a way to build new lists from lists:

my @new = map { $_ * 2 } @list;

And there's a way to get the length of an array:

my $len = $#array;

Put together:

my @even_indexed_elements = @array[map { $_ * 2 } 0 .. int($#array / 2)];

Granted, not quite as nice as the python equivalent, but it does the same job, and you can of course put that in a subroutine if you're using it a lot and want to save yourself from some writing.

Also there's quite possibly something that'd allow writing this in a more natural way in List::AllUtils.

这篇关于是否有一个紧凑的 Perl 操作来切片数组中的替代元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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