【问题标题】:How do I separate unique and duplicate items from two arrays in perl?如何从 perl 中的两个数组中分离唯一和重复项?
【发布时间】:2016-09-23 03:14:10
【问题描述】:

我有这个程序,我想我已经接近了,但我不知道从这里去哪里。我已经进入了循环,我目前正在尝试从唯一数组中删除重复数字并将它们输入到重复数组中。我想我需要使用哈希,但不确定如何去做。任何帮助将不胜感激。

while ($second != -1){
    $second = <STDIN>;
    chomp $second;
    @second[$j] = $second;
    @unique[$j+$i-1] = $second;
    while($x<10){
        if($second == @unique[$x]){
            @duplicate[$x]=$second;
            pop @unique;
        }
        $x++;
    }
    $x=0;
    $j++;
}
pop @second;
pop @unique;

【问题讨论】:

    标签: arrays perl duplicates unique


    【解决方案1】:

    这应该可以完成工作:

    use strict;
    use warnings;
    
    my @original = qw/foo bar hello world foo bar f00 bar barr/; # = array with input data
    my %uniques;
    my @dupes = grep $uniques{$_}++, @original;
    
    print "unique:    ";
    print join ', ', keys %uniques; # output unique elements
    
    print "\nduplicate: ";
    print join ', ', @dupes; # output duplicate elements
    

    输出:

    unique:    foo, barr, hello, f00, world, bar
    duplicate: foo, bar , bar
    

    解释:

    使用grep,您可以查看@original 中的每个数组元素。每个元素(临时放在$_ 中)作为键插入到哈希%uniques 中。哈希不允许在其中包含多个具有相同名称的键,这就是您摆脱重复项的方法。

    【讨论】:

      【解决方案2】:

      下面的程序将遍历@original 并创建两个新数组,每个数组分别用于唯一和重复。 Duplicate 将包含元素n 次,如果它在数组中重复n 次。

      use strict;
      use warnings;
      
      my @original = qw/foo bar hello world foo bar f00 bar barr/; # = array with input data
      
      my %hash = ();
      map {$hash{$_}++} @original;
      my (@uniques, @duplicates) = ((), ());
      for my $key (keys %hash) {
          if ($hash{$key} == 1) {
              push (@uniques, $key);
          } else {
              push (@duplicates, $key) for (1..$hash{$key});
          }
      }
      print "@uniques\n";
      print "=============\n";
      print "@duplicates\n";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-05
        • 2011-12-13
        • 2021-11-30
        • 2012-11-09
        • 1970-01-01
        相关资源
        最近更新 更多