问题描述
数组有很多数据,我需要删除两个元素.
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;
推荐答案
如果您已经知道要删除的元素的索引,请使用 splice.
Use splice if you already know the index of the element you want to delete.
如果您正在搜索,Grep 会起作用.
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.
如果在您的上下文中有意义,您可能需要考虑对已删除的记录使用魔法值",而不是删除它们,以节省数据移动——例如,将删除的元素设置为 undef.自然,这有其自身的问题(如果您需要知道活动"元素的数量,则需要单独跟踪它等),但根据您的应用程序可能值得麻烦.
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.
编辑 实际上,现在我再看一遍——不要使用上面的 grep 代码.找到你要删除的元素的索引,然后用splice删除它会更有效率(你的代码把所有不匹配的结果都累加了..)
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 正确地指出我的示例中有一个错误.. 已修复,对此表示抱歉.
Edit2 John Siracusa correctly pointed out I had a bug in my example.. fixed, sorry about that.
这篇关于从 Perl 中的数组中删除值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!