使用Perl的两个数组的区别

我有两个数组。我需要检查一个元素是否出现在另一个元素中。

有比嵌套循环更有效的方法吗?我每个都有几千个元素,需要经常运行该程序。


偶然的你
浏览 594回答 3
3回答

波斯汪

另一种方法是使用Array :: Utilsuse Array::Utils qw(:all);my @a = qw( a b c d );my @b = qw( c d e f );# symmetric differencemy @diff = array_diff(@a, @b);# intersectionmy @isect = intersect(@a, @b);# unique unionmy @unique = unique(@a, @b);# check if arrays contain same membersif ( !array_diff(@a, @b) ) {        # do something}# get items from array @a that are not in array @bmy @minus = array_minus( @a, @b );

呼如林

perlfaq4 进行救援:如何计算两个数组的差?如何计算两个数组的交集?使用哈希。这是同时执行更多操作的代码。假定每个元素在给定数组中都是唯一的:   @union = @intersection = @difference = ();    %count = ();    foreach $element (@array1, @array2) { $count{$element}++ }    foreach $element (keys %count) {            push @union, $element;            push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;    }如果正确声明了变量,则代码看起来更像以下内容: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;}

BIG阳

您需要提供更多上下文。有更有效的方法可以做到:走出Perl并使用shell(sort+ comm)map一个数组放入Perl哈希,然后遍历另一个数组,检查哈希成员身份。这具有线性复杂度(“ M + N”-基本上循环遍历每个数组一次),而嵌套循环则具有“ M * N”个复杂度)例: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使用为您做最后一点的Perl模块(注释中提到了List :: Compare)如果卷很大,则需要根据添加元素的时间戳进行操作,并且需要经常进行比较。几千个元素还不够大,但是我最近不得不比较10万个列表。
打开App,查看更多内容
随时随地看视频慕课网APP