亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用Perl的兩個數組的區別

使用Perl的兩個數組的區別

我有兩個數組。我需要檢查一個元素是否出現在另一個元素中。有比嵌套循環更有效的方法嗎?我每個都有幾千個元素,需要經常運行該程序。
查看完整描述

3 回答

?
九州編程

TA貢獻1785條經驗 獲得超4個贊

另一種方法是使用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 );



查看完整回答
反對 回復 2019-12-16
?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

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;

}



查看完整回答
反對 回復 2019-12-16
?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

您需要提供更多上下文。有更有效的方法可以做到:


走出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萬個列表。



查看完整回答
反對 回復 2019-12-16
  • 3 回答
  • 0 關注
  • 705 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號