让我们很容易做到这一点。我想要的是:
@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.
如何打印数组/哈希的重复值?
让我们很容易做到这一点。我想要的是:
@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;
}
您想要做的更详细、更易读的版本:
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;
}
这可以大大缩短,但我故意让它冗长,以便您可以跟进。
不过,我没有对其进行测试,因此请注意我的拼写错误。
# 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";
使用字典,将值放入键中,将计数放入值中。
啊,刚刚注意到你标记为 perl
尽管 ([...]) { $哈希{[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, @_;
}