循环遍历列表(或数组)时,有没有办法知道循环中当前元素的索引?
当然,问题可以通过索引循环来解决:
my @aa = 8 .. 12;
say "$_\t@aa[$_]" for 0 ..^ @aa.elems;
但也许可能会出现以下内容(我用.CURRENT_INDEX
标记了我正在寻找的方法)?
my @aa = 8 .. 12;
say $_.CURRENT_INDEX\t$_ for @aa;
答案 0 :(得分:5)
要在列表中获取循环的当前元素的循环索引,可以使用列表的.kv
方法。它返回一个交错的索引和值序列:
my @aa = 8 .. 12;
for @aa.kv -> $i, $_ { say "$i: $_" }
<强>输出强>:
0: 8
1: 9
2: 10
3: 11
4: 12
答案 1 :(得分:3)
这就是真正发生的事情:
my @aa = 8 .. 12;
my \iterator = @aa.iterator;
while ($_ := iterator.pull-one) !=:= IterationEnd {
say $_
}
在这种情况下,iterator
中的值是一个执行Iterator角色的匿名类。
Iterator可能有也可能无法知道它产生了多少值。例如,.roll(*)
的{{3}}不需要知道它到目前为止产生了多少值,因此它不会。
Iterator可以实现一个返回其当前索引的方法。
my @aa = 8 .. 12;
my \iterator = class :: does Iterator {
has $.index = 0; # declares it as public (creates a method)
has @.values;
method pull-one () {
return IterationEnd unless @!values;
++$!index; # this is not needed in most uses of an Iterator
shift @!values;
}
}.new( values => @aa );
say "{iterator.index}\t$_" for Seq.new: iterator;
1 8
2 9
3 10
4 11
5 12
您也可以在更高级别的构造中执行此操作;
my @aa = 8 .. 12;
my $index = 0;
my $seq := gather for @aa { ++$index; take $_ };
say "$index\t$_" for $seq;
要使$_.CURRENT-INDEX
起作用,需要包装结果。
class Iterator-Indexer does Iterator {
has Iterator $.iterator is required;
has $!index = 0;
method pull-one () {
my \current-value = $!iterator.pull-one;
# make sure it ends properly
return IterationEnd if current-value =:= IterationEnd;
# element wrapper class
class :: {
has $.CURRENT-INDEX;
has $.value;
# should have a lot more coercion methods to work properly
method Str () { $!value }
}.new( CURRENT-INDEX => $!index++, value => current-value )
}
}
multi sub with-index ( Iterator \iter ){
Seq.new: Iterator-Indexer.new: iterator => iter;
}
multi sub with-index ( Iterable \iter ){
Seq.new: Iterator-Indexer.new: iterator => iter.iterator;
}
my @aa = 8 .. 12;
say "$_.CURRENT-INDEX()\t$_" for with-index @aa.iterator;
# note that $_ is an instance of the anonymous wrapper class
再次使用更高级别的构造:
my @aa = 8 .. 12;
my \sequence := @aa.kv.map: -> $index, $_ {
# note that this doesn't close over the current value in $index
$_ but role { method CURRENT-INDEX () { $index }}
}
say "$_.CURRENT-INDEX()\t$_" for sequence;
我认为如果你想要这样的话,你应该使用.pairs
。 (或使用.kv
,但基本上需要使用for
的块形式和两个参数)
my @aa = 8 .. 12;
say "$_.key()\t$_.value()" for @aa.pairs;
答案 2 :(得分:1)
这是另一种方式,使用您自己的索引变量:
my @aa = 8..12;
say $++, ": $_" for @aa;
<强>输出:强>
0: 8
1: 9
2: 10
3: 11
4: 12