Perl에서 배열 또는 해시에서 중복 값을 저장하려면 어떻게합니까?
-
05-07-2019 - |
문제
이것을 매우 쉽게 만들어 봅시다. 내가 원하는 것 :
@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.
배열/hash의 중복 값을 인쇄하는 방법은 무엇입니까?
해결책
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