Perl取兩組資料的並集 交集 差集等

2021-09-05 11:54:52 字數 2922 閱讀 3274

目前自己編寫和網上查閱到比較方便的三種方法。

目錄

1. 自寫指令碼,較繁瑣

2. 來自zk1878的指令碼,短小精悍

3. array::utils包,簡便

4. data::dumper包,較簡便

1. **如下:

#! /usr/bin/perl

use warnings;

use strict;

open a, $argv[0] or die;

open b, $argv[1] or die;

open union, '>', "union.txt" or die;

open intsec, '>', "intsec.txt" or die;

open diff, '>', "diff.txt" or die;

open a_spec, '>', "a_spec.txt" or die;

open b_spec, '>', "b_spec.txt" or die;

my @a;

my @b;

while ()

while ()

my @union;#並集

my @diff; #差集

my @intsec;#交集

my @a_spec;

my @b_spec;

my %union;

my %intsec;

my %a;

my %b;

foreach (@a) ++; $a++;}

foreach (@b) ++; $b++;}

@union = keys %union;

foreach (@union) and $union == 1)

elsif ($union == 1 and $b == 1)

else

}@diff = (@a_spec, @b_spec);

print union (join "\n",@union);

print intsec (join "\n",@intsec);

print diff (join "\n", @diff);

print a_spec (join "\n", @a_spec);

print b_spec (join "\n", @b_spec);

2. 參考親測非常好用,**如下:

@a=('a'..'c',1..3);  

@b=('a'..'c',1..3);

@union=();#並集

@diff=(); #差集

@isect=();#交集

foreach $e(@a,@b)++&&$isect++;

} @union=keys %union;

@isect=keys %isect;

@diff=grep ==1;} @union;

print (join ',',@union);

print "\n";

print (join ',',@isect);

print "\n";

print (join ',', @diff);

輸出:

a,a,3,b,2,c,1,c,b  

1,3,2

a,a,b,c,c,b

3. 參考 目測也非常簡便,但沒有試:

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) )

# get items from array @a that are not in array @b

my @minus = array_minus( @a, @b );

4. 參考沒試,**如下:

#!/usr/bin/perl 

use strict;

use warnings;

use data::dumper;

my @a = (1,2,3,4,5,6,7,8,);

my @b = (1,9,0,4,15,6,12,8);

my %hash_a = map @a;

my %hash_b = map @b;

my %merge_all = map @a,@b;

my @a_only = grep } @a;

my @b_only = grep } @b;

my @common = grep } @b;

my @merge = keys (%merge_all);

print "a only :\n";

print dumper(\@a_only);

print "b only :\n";

print dumper(\@b_only);

print "common :\n";

print dumper(\@common);

print "merge :\n";

print dumper(\@merge);

Postgresql取並集,交集,差集

關鍵字union 例子 query1 union query2 關鍵字intersect 例子 query1 intersect query2 關鍵字except 例子 query1 except query2 其中query1和query2的select子句中欄位個數必須相同,且對應的資料型別必須...

C 對List取交集 差集以及並集

list以string型別為例,實際應用中可換做其他型別 1 取交集 取交集 static void intersection listlist2 new list listlist3 new list list3 list1.intersect list2 tolist console.write...

java set 的交集,並集,差集

近日做專案,有個需求是這樣的,有個map1,map2,這兩個map的key有可能是重複的,如果有重複的key,則找出重複的key,然後刪除map1中重複的key以及value,以map2為準,但是map1下面還有用處。然後想到用set求交集不就好了,於是這樣做了 set set1 map1.keys...