【问题标题】:How to merge two arrays without any duplicates如何合并两个没有任何重复的数组
【发布时间】:2011-03-16 10:11:44
【问题描述】:
@tools = ("hammer", "chisel", "screwdriver", "boltcutter",
           "tape", "punch", "pliers"); 
@fretools =("hammer", "chisel", "screwdriver" ,"blade");

push @tools,@fretools if grep @tools,@fretools

我有工具

  @tools=("hammer", "chisel", "screwdriver", "boltcutter", 
       "tape", "punch", "pliers", "blade");

有什么简单的方法吗?

【问题讨论】:

  • 所以你想合并两个没有重复的数组?
  • YES .. 请,我不是在寻找一些外部模块来做这个
  • my @employees1 = ("Fred Flintstone", "Barny Rubble", "Dino Fintstone");我的@employees2 = ("Wilma Flintson", "Bamm-Bamm", "Jigglypuff");我的@allemployees = (@employees1, @employees2); (可能是这个)?
  • @Kinopiko:发布聊天链接可能还没有帮助,因为在“半私人”测试期间需要最低限度的元代表。

标签: perl


【解决方案1】:

List::MoreUtils CPAN 模块有一个uniq 函数来执行此操作。如果您不想依赖这个模块来安装,您可以简单地从模块的源代码中复制uniq 函数(因为它是纯Perl)并将其直接粘贴到您自己的代码中(带有适当的确认)。一般而言,使用 CPAN 代码的优势在于其行为已记录在案且经过良好测试。

use strict;
use warnings;
use Data::Dumper;

sub uniq (@) {
    # From CPAN List::MoreUtils, version 0.22
    my %h;
    map { $h{$_}++ == 0 ? $_ : () } @_;
}

my @tools = ("hammer", "chisel", "screwdriver", "boltcutter",
             "tape", "punch", "pliers"); 
my @fretools =("hammer", "chisel", "screwdriver" ,"blade");
@tools = uniq(@tools, @fretools);
print Dumper(\@tools);

__END__

$VAR1 = [
          'hammer',
          'chisel',
          'screwdriver',
          'boltcutter',
          'tape',
          'punch',
          'pliers',
          'blade'
        ];

【讨论】:

  • +1 更紧凑的变体:map { $h{$_}++ ? () : $_ } @_
【解决方案2】:

肯定有一个模块可以为您执行此操作,但没有模块:

my %uniques;
@uniques{@tools} = @tools x (1);
@uniques{@fretools} = @fretools x (1);
@tools = sort keys %uniques;

这会将工具置于不同的顺序。如果你想保持订单,你需要一个不同的方法。

my %uniques;
@uniques{@tools} = @tools x (1);
for (@fretools) {
    push @tools, $_ if ! $uniques{$_};
}

【讨论】:

    【解决方案3】:

    您可以尝试使用哈希,然后提取键以获取唯一元素:

    use strict; 
    
    my @tools = ("hammer", "chisel", "screwdriver", "boltcutter", "tape", "punch", "pliers");  
    my @fretools =("hammer", "chisel", "screwdriver" ,"blade"); 
    
    push @tools,@fretools if grep @tools,@fretools;
    
    my %hash   = map { $_, 1 } @tools;
    my @array = keys %hash;
    
    print "@array";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多