Perlで配列またはハッシュから重複した値を保存するにはどうすればよいですか?
-
05-07-2019 - |
質問
これを非常に簡単にしましょう。欲しいもの:
@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, @_;
}
所属していません StackOverflow