Perl根据使用grep的条件分割数组(Perl splitting array based on condition using grep)

系统教程 行业动态 更新时间:2024-06-14 17:01:34
Perl根据使用grep的条件分割数组(Perl splitting array based on condition using grep)

我有一些看起来像这样的Perl代码:

my @array = map { rand } ( 1..100 ); my @matching = grep { $_ == $condition } @array; @array = grep { $_ != $condition } @array;

这工作正常,但我想要做的是基于一个单一的操作将原始数组拆分为两个......我认为我执行的操作数是严格必要的两倍。

帮助赞赏! 谢谢。

I have some perl code that looks something like this:

my @array = map { rand } ( 1..100 ); my @matching = grep { $_ == $condition } @array; @array = grep { $_ != $condition } @array;

This works ok, but what I would like to do is split the original array into two based on a single operation...I think I'm carrying out twice as many operations as strictly necessary.

Help appreciated!! Thanks.

最满意答案

到目前为止,最简单的方法是迭代数组,并根据条件将值推送到两个数组中的任一个,如下例所示。

for (@array) { if ($_ % 2) {push @odd, $_} else {push @even, $_} }

如果你想修改源数组:

for (my $i =0; $i < @array; ++$i) { if ($array[$i] % 2) { push @odd, splice (@array, $i--, 1); } }

你为什么不推荐List :: MoreUtils :: part?

有问题的模块可能不存在于目标系统上,这总是令人讨厌的事情。

同样在系统上,我运行了测试,发现List::MoreUtils::part速度是本篇文章的第一个片段的两倍,尽管对于不同的part实现它实际上可能是相反的。

By far the easiest method is to iterate your array and push values to either of the two arrays depending on the condition, as in the below example.

for (@array) { if ($_ % 2) {push @odd, $_} else {push @even, $_} }

If you'd like to modify the source array:

for (my $i =0; $i < @array; ++$i) { if ($array[$i] % 2) { push @odd, splice (@array, $i--, 1); } }

Why didn't you recommend List::MoreUtils::part?

The module in question might not exists on the target system, which is always an annoying thing.

Also on the system I ran tests on I found that List::MoreUtils::part was twice as slow as first snippet in this post, though with different implementations of part it might be the opposite actually.

更多推荐

本文发布于:2023-04-20 18:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/84089b47aa619803494da8871d08e024.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   条件   grep   Perl   condition

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!