如何在perl中获取数组中最大重复值的所有索引
大家好,我是 Perl 新手,正在学习过程中。 我有一个数组,
@array = ( 10, 40, 59, 40, 90, 100, 30, 40, 100, 20, );
我想找到数组中的最大数字,并且还想知道数组中存在最大数字的索引。
我正在做的
my $maxValue = max @array;
print $maxValue; # displays the maximum number in the entire array
my ($index) = grep $array[$_] eq $maxValue , 0.. $#array;
print ($index); # this gives me the index of the maximum number which was found in the array.
输出是索引为 5 的 100
但实际上 100 在数组中出现了 2 次:一次在索引 6 处,另一次在索引 8 处。我的代码只向我提供它找到的具有最大值的第一个索引。
如何获得所有具有最大值的索引?
Hi I am new to Perl an in a learning process.
I am having an array
@array = ( 10, 40, 59, 40, 90, 100, 30, 40, 100, 20, );
I want to find the maximum number in the array and also want to know the index where the maximum number is present in my array.
I am doing
my $maxValue = max @array;
print $maxValue; # displays the maximum number in the entire array
my ($index) = grep $array[$_] eq $maxValue , 0.. $#array;
print ($index); # this gives me the index of the maximum number which was found in the array.
The output I am getting is 100 with index 5
But actually 100 is coming 2 times in the array: once at index 6 and again at index 8. My code only provide me the first index it finds with the max value.
How can I get all the index which has maximum value with them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
似乎是最简单的方法。
尽管对于数字,您确实应该使用
==
,即使例如 100 也是一个有效的字符串。Seems to be the simplest way.
Although for numbers, you really should use
==
, even though e.g. 100 is also a valid string.这是一次通过数组来确定最大值和所有索引:
另一种方法...没有哈希:
This is one time through the array to determine the max value and all the indexes:
Another way... without the hash: