让我们轻松一点。我想要的是什么:

@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.

如何打印数组/哈希的重复值?

有帮助吗?

解决方案

sub duplicate {
    my @args = @_;
    my %items;
    for my $element(@args) {
        $items{$element}++;
    }
    return grep {$items{<*>} > 1} keys %items;
}

其他提示

# assumes inputs can be hash keys
@a = (1, 2, 3, 3, 4, 4, 5);

# keep count for each unique input
%h = ();
map { $h{<*>}++  } @a;

# duplicate inputs have count > 1
@dupes = grep { $h{<*>} > 1 } keys %h;

# should print 3, 4
print join(", ", sort @dupes), "\n";

您想要做的额外详细,额外可读的版本:


sub duplicate {
   my %value_hash;
   foreach my $val (@_) {
     $value_hash{$val} +=1;
   }
   my @arr;
   while (my ($val, $num) = each(%value_hash)) {
     if ($num > 1) {
        push(@arr, $val)
     }
   }
  return @arr;
}

这可以大大缩短,但我故意将其冗长,以便您可以跟进。

但是,我没有测试它,所以请注意我的错别字。

使用字典,将值放入键中,将计数值放入值中。

啊,刚刚注意到你已被标记为perl

while ([...]) {
 $hash{[dbvalue]}++
}

问题中未指明的是应该返回重复项的顺序。

我可以想到几种可能性:不在乎;按输入列表中第一个/第二个/最后一个出现的顺序;排序

我要去打高尔夫球了!

sub duplicate {
    my %count;
    grep $count{

我要去打高尔夫球了!

<*>}++, @_; } @array = qw/one two one/; my @duplicates = duplicate(@array); print "@duplicates"; # This should now print 'one'. # or if returning *exactly* 1 occurrence of each duplicated item is important sub duplicate { my %count; grep ++$count{

我要去打高尔夫球了!

<*>} == 2, @_; }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top