我有一个数字列表 L 。还有另一个数字列表 M 。我需要返回在 L 和 M 中都找到的数字列表 L'。
编辑:数学上,我正在寻找Multiset交集。
例子:
L = 3,
1
, 4,1
, 5,9
,2
, 6
M =9
, 7,1
,2
,1
, 1
L' = 9, 1, 2, 1
我为此写了following code:
my @some-numbers = 3, 1, 4, 1, 5, 9, 2, 6;
my @to-match = 9, 7, 1, 2, 1, 1;
my @matched;
my %histogram;
for @some-numbers -> $n { %histogram{$n}++ };
for @to-match -> $n {
next if not defined %histogram{$n};
if %histogram{$n} > 0 {
push @matched, $n;
%histogram{$n}--;
}
};
say @matched;
当它达到目的时,我想知道是否有一种惯用的Perl6方法来做到这一点?
背景知识:我一直在尝试一起学习Perl6和Python,并用两种语言解决相同的难题。 Python为上述问题提供了一个特别的pleasing solution。至少对我的初学者而言:)
最佳答案
根据您要查找的精确语义,Bag操作可能只是故障单:
my \L = 3, 1, 4, 1, 5, 9, 2, 6;
my \M = 9, 7, 1, 2, 1, 1;
.put with L.Bag ∩ M.Bag;
显示:
9 1(2) 2
这是
Bag
的字符串化,包含三个键'9'
,'1'
和'2'
,它们的各自值(重复计数)是整数1
,2
和1
。要使Perl 6从包中产生一个列表,并且每个键重复其关联值指示的次数,请使用
.kxxv
方法:.kxxv.put with L.Bag ∩ M.Bag;
显示:
9 1 1 2
(
kxxv
方法的助记符是,它是“key”的k
,然后类似于 xx
重复运算符,最后是xx
的“value”,是v
。如果您考虑一下,这有点有意义。)但是也许一个袋子不会做。例如,结果中元素的顺序可能很重要-您需要
9 1 2 1
而不是9 1 1 2
吗?如果提包不正确,我将回答这个问题。
关于raku - Perl6 : Match elements in a list with another list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43147958/