简体   繁体   English

在Perl中使用'unique'时如何从数组中查找'non-unique'值

[英]How to find 'non-unique' value from array when using 'unique' in perl

my @words = qw(1 2 3 4 4);
my @unique_words = uniq @words;

print @unique_words; # 1 2 3 4

I am interested in finding which value was non-unique, in this case 4 . 我有兴趣找出哪个值是非唯一的,在这种情况下为4 And being able to set it equal to a variable so that I can keep track of which specific value was re-occuring. 并能够将其设置为等于变量,这样我就可以跟踪重新出现哪个特定值。

I want to do this so I can implement a code that says "if my string contains duplicating value from array completely remove duplicating value from array from string". 我想这样做,所以我可以实现一个代码,说“如果我的字符串包含来自数组的重复值,则完全删除来自字符串的数组中的重复值 ”。 In this case, if a string contained 1 2 3 4 4 . 在这种情况下,如果字符串包含1 2 3 4 4 I would like it after the if statement to contain 1 2 3 . 我希望if语句后包含1 2 3

Counting/finding duplicates is easiest done with a hash: 计算/查找重复项最简单的方法是使用哈希:

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

Finding the values that only occur once is done by looking for the elements in %count that have a count of 1: 通过在%count中查找计数为1的元素来查找仅出现一次的值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM