【问题标题】:comparison of two arrays and finding the missing elements and from which array in perl比较两个数组并找到丢失的元素以及perl中的哪个数组
【发布时间】:2017-08-17 01:35:06
【问题描述】:

我有两个数组。我需要找出数组的共同元素以及缺少哪些元素以及来自哪个数组?

我正在使用下面的代码来查找两个数组中的公共元素以及两个数组中缺失元素的列表。

谁能告诉我如何从每个数组中找到missing的元素列表?

例如: 在下面的代码中,我需要打印 @arr2 中缺少的元素 "ghi"@arr1

中缺少的元素 "mno"
my @arr1 = ( "abc", "def", "ghi", "jkl" ); 
my @arr2 = ( "mno", "abc", "jkl", "def" );

my %count = ();
foreach $element ( @arr1, @arr2 ){
    $count{$element}++;
}
my @diff = grep { $count{$_} == 1 } keys %count;
my @common = grep { $count{$_} == 2 } keys %count;

【问题讨论】:

标签: arrays perl compare


【解决方案1】:

如果您将@arr1@arr2 的项目也放入哈希中,您可以这样做:

my @miss1 = grep { $count{$_} == 1 && !exists $arr1{$_} } keys %count;
my @miss2 = grep { $count{$_} == 1 && !exists $arr2{$_} } keys %count;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    相关资源
    最近更新 更多