什么是删除Perl中的数组值的最佳方法? [英] What is the best way to delete a value from an array in Perl?

查看:124
本文介绍了什么是删除Perl中的数组值的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该阵列具有大量的数据,我需要删除两个元素。

下面是我使用code片段,

 我@array =(1,2,3,4,5,5,6,5,4,9);
我的$ element_omitted = 5;
@array = {grep的$ _ = $ element_omitted!} @array;


解决方案

使用剪接如果你已经知道你要删除的元素的索引。

grep的工作,如果你正在寻找。

如果你需要做大量的这些,你会如果你保持你的数组中的排序顺序获得更好的性能,因为你可以然后做二进制搜索找到所需的索引。

如果是有意义的上下文,你可能要考虑使用魔术价值为删除的记录,而不是删除它们,以节省数据移动 - 集中删除元素民主基金,例如。当然,这有它自己的问题(如果你需要知道的活元素的数量,你需要保持它的轨道分开等),但可能会根据您的应用程序的麻烦值得的。

修改其实现在,我仔细看一下 - 不要使用grep code以上。这将是更有效的找到要删除,然后用剪接把它删除的元素的索引(code你有积累的所有非匹配的结果..)

 我的$ index = 0;
$指数++,直到$改编[$指数] EQ'富';
拼接(@arr,$指数,1);

这将删除第一次出现。
删除所有事件非常相似,但你会希望得到各指标在一通:

 我@del_indexes =的grep {$改编[$ _] EQ'富'} 0 .. $#编曲;

剩下的留作为读者提供一个锻炼; Tibial - 记住,数组的变化,你拼接它

EDIT2 约翰·锡拉库扎正确地指出,我有一个错误在我的例子..固定的,我们对此深感抱歉。

The array has lots of data and I need to delete two elements.

Below is the code snippet I am using,

my @array = (1,2,3,4,5,5,6,5,4,9);
my $element_omitted = 5;
@array = grep { $_ != $element_omitted } @array;

解决方案

Use splice if you already know the index of the element you want to delete.

Grep works if you are searching.

If you need to do a lot of these, you will get much better performance if you keep your array in sorted order, since you can then do binary search to find the necessary index.

If it makes sense in your context, you may want to consider using a "magic value" for deleted records, rather then deleting them, to save on data movement -- set deleted elements to undef, for example. Naturally, this has its own issues (if you need to know the number of "live" elements, you need to keep track of it separately, etc), but may be worth the trouble depending on your application.

Edit Actually now that I take a second look -- don't use the grep code above. It would be more efficient to find the index of the element you want to delete, then use splice to delete it (the code you have accumulates all the non-matching results..)

my $index = 0;
$index++ until $arr[$index] eq 'foo';
splice(@arr, $index, 1);

That will delete the first occurrence. Deleting all occurrences is very similar, except you will want to get all indexes in one pass:

my @del_indexes = grep { $arr[$_] eq 'foo' } 0..$#arr;

The rest is left as an excercise for the reader -- remember that the array changes as you splice it!

Edit2 John Siracusa correctly pointed out I had a bug in my example.. fixed, sorry about that.

这篇关于什么是删除Perl中的数组值的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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