3 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
另一種方法是使用Array :: Utils
use Array::Utils qw(:all);
my @a = qw( a b c d );
my @b = qw( c d e f );
# symmetric difference
my @diff = array_diff(@a, @b);
# intersection
my @isect = intersect(@a, @b);
# unique union
my @unique = unique(@a, @b);
# check if arrays contain same members
if ( !array_diff(@a, @b) ) {
# do something
}
# get items from array @a that are not in array @b
my @minus = array_minus( @a, @b );

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊
perlfaq4 進(jìn)行救援:
如何計(jì)算兩個(gè)數(shù)組的差?如何計(jì)算兩個(gè)數(shù)組的交集?
使用哈希。這是同時(shí)執(zhí)行更多操作的代碼。假定每個(gè)元素在給定數(shù)組中都是唯一的:
@union = @intersection = @difference = ();
%count = ();
foreach $element (@array1, @array2) { $count{$element}++ }
foreach $element (keys %count) {
push @union, $element;
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}
如果正確聲明了變量,則代碼看起來更像以下內(nèi)容:
my %count;
for my $element (@array1, @array2) { $count{$element}++ }
my ( @union, @intersection, @difference );
for my $element (keys %count) {
push @union, $element;
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
您需要提供更多上下文。有更有效的方法可以做到:
走出Perl并使用shell(sort+ comm)
map一個(gè)數(shù)組放入Perl哈希,然后遍歷另一個(gè)數(shù)組,檢查哈希成員身份。這具有線性復(fù)雜度(“ M + N”-基本上循環(huán)遍歷每個(gè)數(shù)組一次),而嵌套循環(huán)則具有“ M * N”個(gè)復(fù)雜度)
例:
my %second = map {$_=>1} @second;
my @only_in_first = grep { !$second{$_} } @first;
# use a foreach loop with `last` instead of "grep"
# if you only want yes/no answer instead of full list
使用為您做最后一點(diǎn)的Perl模塊(注釋中提到了List :: Compare)
如果卷很大,則需要根據(jù)添加元素的時(shí)間戳進(jìn)行操作,并且需要經(jīng)常進(jìn)行比較。幾千個(gè)元素還不夠大,但是我最近不得不比較10萬個(gè)列表。
添加回答
舉報(bào)