perl 数组对比 删相同元素

perl 数组对比 删相同元素


慕哥9229398
浏览 655回答 3
3回答

largeQ

这是经典的集合差运算,下面的代码还演示了集合并集、交集的运算,只是没有输出结果,请自行理解,完整代码如下:@a=('1','2','3','4');@b=('1','3');@union=();#并集@diff=(); #差集@isect=();#交集foreach $e(@a,@b){$union{$e}++&&$isect{$e}++;}@union=keys %union;@isect=keys %isect;@diff=grep {$union{$_}==1;} @union;print join(',', @a),"\n";print join(',', @b),"\n";print join(',', @diff),"\n";

当年话下

my %h = ();++$h{$_} foreach ( @array1, @array2 );my @array3 = sort keys %h;

PIPIONE

my @array1 = ('aa', 'bb');my @array2 = ('cc', 'aa');@array3 = (@array1, @array2);my %count;my @array3_new = grep { ++$count{ $_ } < 2; } @array3;print @array3_new;或者@array3 = (@array1, @array2);foreach my $item ( @array3 ){if ( ! grep( /$item/, @array3_new ) ){push( @array3_new, $item );}}print @array3_new;
打开App,查看更多内容
随时随地看视频慕课网APP