[英]What's the Perl equivalent of Python's enumerate?
I'm looking for a function in Perl 5 that works similarly to Python's enumerate
built-in. 我正在寻找Perl 5中的一个函数,它与Python的
enumerate
内置函数类似。 It would return a list of references to arrays, where each array is [$index, $element]
: 它将返回一个对数组的引用列表,其中每个数组都是
[$index, $element]
:
@a = ("a", "b", "c");
@b = enumerate @a;
# @b = ([0, "a"], [1, "b"], [2, "c"])
List::Util and List::MoreUtils don't seem to have this function. List :: Util和List :: MoreUtils似乎没有这个功能。 Is there another module that does?
还有其他模块吗?
You can use map
, like this 你可以像这样使用
map
my @data = qw / a b c /;
my @enumeration = map [ $_, $data[$_] ], 0 .. $#data;
Perl doesn't have a built-in function to do that but it's easy to roll your own. Perl没有这样做的内置功能,但它很容易推出自己的功能。
Using map
: 使用
map
:
my @a = qw(a b c);
my $i = 0;
my @b = map [$i++, $_], @a; # ([0, 'a'], [1, 'b'], [2, 'c'])
As of v5.20, Perl's new slice syntax does something similar: 从v5.20开始,Perl的新切片语法做了类似的事情:
my @a = qw(a b c);
my @b = %a[0..$#a]; # (0, 'a', 1, 'b', 2, 'c')
That slice syntax returns a list of index/value pairs but it's a flat list. 该切片语法返回索引/值对列表,但它是一个平面列表。 The pairs aren't grouped into nested arrays.
这些对不会分组为嵌套数组。 If that's important to your application you can use the pairmap function from List::Util to do it:
如果这对您的应用程序很重要,您可以使用List :: Util中的pairmap函数来执行此操作:
use List::Util qw(pairmap);
my @a = qw(a b c);
my @b = pairmap {[$a, $b]} %a[0..$#a]; # ([0, 'a'], [1, 'b'], [2, 'c'])
enumerate
returns an iterator, not a list, so you should really be asking for an iterator. enumerate
返回一个迭代器,而不是一个列表,所以你应该真的要求一个迭代器。
In Perl 5.12.0 and up, you can use each
to iterate over arrays: 在Perl 5.12.0及更高版本中,您可以使用
each
迭代数组:
use strict;
use warnings 'all';
use 5.012;
my @a = qw(foo bar baz);
while (my ($i, $v) = each @a) {
say "$i -> $v";
}
__END__
0 -> foo
1 -> bar
2 -> baz
However, you should be very careful when using each
; 但是,
each
使用时each
应该非常小心; some people even discourage its use altogether . 有些人甚至完全不鼓励使用它 。
Use the List::Enumerate module. 使用List :: Enumerate模块。
use List::Enumerate qw(enumerate);
@a = ("a", "b", "c");
@b = map { [ $_->index, $_->item ] } enumerate(@a);
sub enumerate(&@) {
local *f = shift;
my @array = @_;
my @ret;
my $pkg = caller;
for ( my $i = 0 ; $i < @array ; $i++ ) {
no strict 'refs';
local *{ $pkg . '::a' } = \$i;
local *{ $pkg . '::b' } = \$array[$i];
push @ret, f( $i, $array[$i] );
}
@ret;
}
my @tmp = enumerate { ($a, $b) } 'a'..'z';
say "@tmp";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.