【问题标题】:How to find 'non-unique' value from array when using 'unique' in perl在 perl 中使用“唯一”时如何从数组中查找“非唯一”值
【发布时间】:2018-10-18 18:29:17
【问题描述】:
my @words = qw(1 2 3 4 4);
my @unique_words = uniq @words;

print @unique_words; # 1 2 3 4

我有兴趣找出哪个值是非唯一的,在本例中为 4。并且能够将其设置为一个变量,以便我可以跟踪重新出现的特定值。

我想这样做,所以我可以实现一个代码,上面写着“如果我的字符串包含 数组中的重复值,则完全从字符串中删除 数组中的重复值”。在这种情况下,如果一个字符串包含1 2 3 4 4。我希望在 if 语句之后包含 1 2 3

【问题讨论】:

  • @toolic 感谢您的回复!如何使用此代码实现打印多次计数的值?

标签: string perl unique


【解决方案1】:

使用哈希最容易计算/查找重复项:

my %count;
$count{ $_ }++ for @words;
print "$_ occurs more than once\n"
    for grep { $count{ $_ } > 1 } @words;

通过在%count 中查找计数为 1 的元素来查找仅出现一次的值:

my %count;
$count{ $_ }++ for @words;
my @unique_words = grep { $count{ $_ } == 1 } @words;

【讨论】:

  • 谢谢你的工作!无论如何,我可以将 $_ 设置为等于保存多次出现的值的变量吗?这样我就可以在我的程序中进行全局比较?非常感谢您提前指导。
  • “多次出现的值”是什么意思?可以有不止一个值出现不止一次。表达式grep { $count{ $_ } > 1 } keys %count; 返回多次出现的所有值。您可以使用 my @duplicates = grep { $count{ $_ } > 1 } keys %count; 保留该列表。
  • 或使用my @non_duplicates = grep { $count{$_} == 1 } @words;列出仅非重复值的列表
  • @ysth 非常感谢。这有很大帮助。我想这就是我一直在寻找的。​​span>
  • @Corion 谢谢你,帮了大忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-09
  • 2017-05-07
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 2015-05-10
  • 2016-11-08
相关资源
最近更新 更多