问题描述
确定数组A中不在数组B中的项目的快速方法是什么?
What is a quick way to determine items in array A that are not in array B?
到目前为止,我有以下内容,但是可以一行完成吗?
So far I have the following, but can it be done in one line?
for $aname (@anames)
{
if (not grep { $_ eq $aname } @hrefs)
{
push @anamesremove, $aname;
}
}
推荐答案
如果您知道哪个数组包含另一个数组
If you know which array contains the other
my @small = 10..12;
my @large = 10..15;
my %ref = map { $_ => 1 } @small;
my @diff = grep { not exists $ref{$_} } @large;
行数不多,但效率很高.
Not quite one line but efficient.
如果不知道其中包含另一个,则必须双向进行.
If it's not known which contains the other then one has to do it both ways.
然后有各种用于阵列/列表操作的模块可以提供帮助.
And then there are various modules for array/list manipulation that can help.
其中之一,来自 List :: Compare 的get_complement
正是需要的
For one, get_complement
from List::Compare does precisely what is needed.
您可以使用 List :: Util 在一个语句中完成所有操作
What you have can be done in one statement, using List::Util
use List::Util qw(none);
my @diff = grep { my $e = $_; none { $e eq $_ } @small } @large;
但这具有 O(NM-M /2)复杂度,其中 N (大)和 M (小)是数组大小.
but this has O(NM-M/2) complexity, where N (large) and M (small) are array sizes.
这篇关于不在数组B中的数组A中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!