【问题标题】:To remove duplicate elements from an array in Perl在 Perl 中从数组中删除重复元素
【发布时间】:2015-02-10 06:08:12
【问题描述】:

我有一个数据集

10-101570715-101609901-hsa-mir-3158-1   10-101600739-101609661-ENSG00000166171  10-101588288-101609668-ENSG00000166171  10-101588325-101609447-ENSG00000166171  10-101594702-101609439-ENSG00000166171  10-101570560-101596651-ENSG00000166171  

10-103389007-103396515-hsa-mir-1307 10-103389041-103396023-ENSG00000173915  10-103389050-103396074-ENSG00000173915  10-103389050-103396441-ENSG00000173915  10-103389050-103396466-ENSG00000173915  10-103389050-103396466-ENSG00000173915

除了每一行的第一个元素外,我有多个值,这些值是多余的,我想删除多余的值。我写了一段代码,但我觉得它工作得不好。

open (fh, "file1");
while ($line=<fh>)
{
chomp ($line);
@array=$line;
my @unique = ();
my %Seen   = ();
foreach my $elem ( @array )
    {
    next if $Seen{ $elem }++;
    push @unique, $elem;
    }
print @unique;
}

【问题讨论】:

  • use strict; use warnings; use Data::Dumper; print Dumper \%Seen; 你不是在寻找使用完整行的重复项吗?
  • 不,不使用整行重复,只搜索在一行内重复的元素

标签: arrays perl duplicates elements


【解决方案1】:

哈希用于重复检测:

my %seen;
my @removeduplicate = grep { !$seen{$_}++ } @array;

对我来说,下面的代码工作正常:

use strict;
use warnings;

my %seen;
open my $fh, "<", 'file.txt' or die "couldn't open : $!";
while ( my $line = <$fh>)
{
    chomp $line;
    my @array = split (' ', $line);
    my @removeduplicate = grep { !$seen{$_}++ } @array;
    print "@removeduplicate\n";
}

【讨论】:

  • 冗余值仍然存在
  • @MANAUWERRAZA:看看我编辑的答案。始终使用use warningsuse strict 以及三个参数进行文件操作。
  • 谢谢,之前写的代码也能用,完全是我的疏忽……
  • 如果这对您有帮助,您可以选择此作为回答。
猜你喜欢
  • 2013-12-10
  • 1970-01-01
  • 2013-05-20
  • 2011-07-03
  • 2013-07-29
  • 2017-03-21
  • 2014-11-02
  • 1970-01-01
相关资源
最近更新 更多