我如何在 perl 6 中“展平”列表列表?
How do I “flatten” a list of lists in perl 6?
假设我想要 a、b 和 c 中 2 个字母的所有排列。
我能做到:
my @perm = <a b c>.combinations(2)».permutations;
say @perm;
# [((a b) (b a)) ((a c) (c a)) ((b c) (c b))]
这很接近,但不完全是我需要的。
我如何“扁平化”它以便我得到:
# [(a b) (b a) (a c) (c a) (b c) (c b)]
?
根据需要插入slips,例如通过
<a b c>.combinations(2).map(*.permutations.Slip).Array
或
[ slip .permutations for <a b c>.combinations(2) ]
如果您对 Seq
没问题,则在第一个示例中调用 .Array
是不必要的,并且可以替换为调用 .list
或 .cache
(已提供通过 PositionalBindFailover) 如果不需要可变性。
在第二个示例中,可以使用前缀 |
运算符代替 slip
子运算符。
my @perm = <a b c>.combinations(2)».permutations;
dd [ @perm.map(*.Slip) ]
# OUTPUT«[("a", "b"), ("b", "a"), ("a", "c"), ("c", "a"), ("b", "c"), ("c", "b")]»
但是,当您稍后在程序中使用它时,您最好解构 LoL。长列表中的地图可能需要很长时间。
另见 。
另见 。
加下标
my \perm = <a b c>.combinations(2)».permutations;
say perm; # (((a b) (b a)) ((a c) (c a)) ((b c) (c b)))
say perm[*]; # (((a b) (b a)) ((a c) (c a)) ((b c) (c b)))
say perm[*;*]; # ((a b) (b a) (a c) (c a) (b c) (c b))
say perm[*;*;*] # (a b b a a c c a b c c b)
备注
我使用了一个非 sigil'd 变量,因为我认为对于那些不了解 Raku 的人来说,它更清楚发生了什么。
我没有将下标附加到原始表达式,但我可以:
my \perm = <a b c>.combinations(2)».permutations[*;*];
say perm; # ((a b) (b a) (a c) (c a) (b c) (c b))
最终,您以错误的方式开始构建列表。您可以像这样 slip
您的排列到外部列表中。
<a b c>.combinations(2).map(|*.permutations);
产生以下列表
((a b) (b a) (a c) (c a) (b c) (c b))
根据 Bench 模块,这比
快了大约 300%
<a b c>.combinations(2).map(*.permutations)[*;*]
假设我想要 a、b 和 c 中 2 个字母的所有排列。
我能做到:
my @perm = <a b c>.combinations(2)».permutations;
say @perm;
# [((a b) (b a)) ((a c) (c a)) ((b c) (c b))]
这很接近,但不完全是我需要的。 我如何“扁平化”它以便我得到:
# [(a b) (b a) (a c) (c a) (b c) (c b)]
?
根据需要插入slips,例如通过
<a b c>.combinations(2).map(*.permutations.Slip).Array
或
[ slip .permutations for <a b c>.combinations(2) ]
如果您对 Seq
没问题,则在第一个示例中调用 .Array
是不必要的,并且可以替换为调用 .list
或 .cache
(已提供通过 PositionalBindFailover) 如果不需要可变性。
在第二个示例中,可以使用前缀 |
运算符代替 slip
子运算符。
my @perm = <a b c>.combinations(2)».permutations;
dd [ @perm.map(*.Slip) ]
# OUTPUT«[("a", "b"), ("b", "a"), ("a", "c"), ("c", "a"), ("b", "c"), ("c", "b")]»
但是,当您稍后在程序中使用它时,您最好解构 LoL。长列表中的地图可能需要很长时间。
另见
另见
加下标
my \perm = <a b c>.combinations(2)».permutations;
say perm; # (((a b) (b a)) ((a c) (c a)) ((b c) (c b)))
say perm[*]; # (((a b) (b a)) ((a c) (c a)) ((b c) (c b)))
say perm[*;*]; # ((a b) (b a) (a c) (c a) (b c) (c b))
say perm[*;*;*] # (a b b a a c c a b c c b)
备注
我使用了一个非 sigil'd 变量,因为我认为对于那些不了解 Raku 的人来说,它更清楚发生了什么。
我没有将下标附加到原始表达式,但我可以:
my \perm = <a b c>.combinations(2)».permutations[*;*];
say perm; # ((a b) (b a) (a c) (c a) (b c) (c b))
最终,您以错误的方式开始构建列表。您可以像这样 slip
您的排列到外部列表中。
<a b c>.combinations(2).map(|*.permutations);
产生以下列表
((a b) (b a) (a c) (c a) (b c) (c b))
根据 Bench 模块,这比
快了大约 300%<a b c>.combinations(2).map(*.permutations)[*;*]