【问题标题】:How do I store a duplicate value from an array or hash in Perl?如何在 Perl 中存储数组或哈希中的重复值?
【发布时间】:2010-09-20 06:51:29
【问题描述】:

让我们让它变得非常简单。我想要什么:

@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.

如何打印数组/哈希的重复值?

【问题讨论】:

  • 不清楚你到底想要完成什么,你能澄清一下吗?
  • 每个人都想从数组/哈希中删除重复值,这很好。但我想保留那个重复的值...
  • @Robert Gamble:不清楚你发现不清楚的地方,你能澄清一下吗? :)
  • @Ysth:问题已被编辑以使其清晰;-)

标签: perl arrays hash duplicates


【解决方案1】:
sub duplicate {
    my @args = @_;
    my %items;
    for my $element(@args) {
        $items{$element}++;
    }
    return grep {$items{$_} > 1} keys %items;
}

【讨论】:

  • 我认为哈希声明后缺少一个分号。
【解决方案2】:
# 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";

【讨论】:

  • $h{$_}++ for @a;,而不是在无效上下文中使用map
【解决方案3】:

你想要做的更详细、更易读的版本:


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;
}

这可以大大缩短,但我故意让它冗长,以便您可以跟进。

不过,我没有测试它,所以请注意我的拼写错误。

【讨论】:

  • @array = qw/one two one/ 是一种完美可接受的书写方式。
  • 我是在 Brian D Foy 解决原始问题之前写的。他最初在那里有标量。但我现在删除了“第一次关闭”评论,因为它不再有意义。
【解决方案4】:

使用字典,将值放入键中,将计数放入值中。

啊,刚刚注意到你标记为 perl

尽管 ([...]) { $哈希{[dbvalue]}++ }

【讨论】:

  • 呃……开始有点晚了,我真的觉得我需要一些代码示例。 ;-)
【解决方案5】:

问题中未指定返回副本的顺序。

我能想到几种可能:不关心;按输入列表中第一次/第二次/最后一次出现的顺序;排序。

【讨论】:

    【解决方案6】:

    我要去打高尔夫球!

    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, @_;
    }
    

    【讨论】:

    • 该代码存在一个问题,即当它出现 3 次或更多次时,它会多次返回一个元素。
    • 另外,你想在它周围加上大括号。
    • 这取决于您是希望返回 3 次中的 2 次,还是只返回 1 次;问题没有具体说明。不需要大括号。
    猜你喜欢
    • 2016-06-16
    • 1970-01-01
    • 2017-10-18
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 2010-12-20
    相关资源
    最近更新 更多