【问题标题】:how to find duplicate array values in perl [duplicate]如何在perl中查找重复的数组值[重复]
【发布时间】:2011-12-18 06:22:55
【问题描述】:

可能重复:
What's the most efficient way to check for duplicates in an array of data using Perl?

如何查找数组中的重复值?

这是我的数组:

@arr - ("one","two","one","three","two");

输出将是:

one
two

代码:

while (<RFH>) {
    chomp;
    @arr = split(/\|/,$_);
    push(@arr1,$arr[4]."\n");
}

【问题讨论】:

  • 为什么“三”不应该出现在输出中?

标签: perl


【解决方案1】:

一次性解决方案:

my %seen = ();
@dup = map { 1==$seen{$_}++ ? $_ : () } @list;

【讨论】:

    【解决方案2】:
     my %cnt;
     $cnt{$_}++ for @arr;
     print "$_\n" for grep $cnt{$_} > 1, keys %cnt;
    

    【讨论】:

      【解决方案3】:

      使用哈希的替代方式:

      my @arr = ("one", "two", "one", "three", "two");
      my %arr_counts;
      for (@arr) { $arr_counts{$_}++ };
      my @dupes = grep { $arr_counts{$_} > 1 } keys %arr_counts;
      

      请注意,哈希不维护排序顺序。它不是随机的,所以如果你使用相同的列表运行,你会得到相同的结果,但实际上顺序会改变。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多