【问题标题】:How do I “flatten” a list of lists in perl 6?如何在 perl 6 中“展平”列表列表?
【发布时间】:2016-09-07 11:13:45
【问题描述】:

假设我想要 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)]

?

【问题讨论】:

标签: raku


【解决方案1】:

另见"a better way to accomplish what I (OP) wanted"

另见"Some possible solutions" answer to "How can I completely flatten a Raku list (of lists (of lists) … )" question

添加下标

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)

注意事项

我使用了一个非印记变量,因为我认为对于那些不了解 Raku 的人来说,它更清楚发生了什么。

我没有将下标附加到原始表达式,但我可以:

my \perm = <a b c>.combinations(2)».permutations[*;*];
say perm;       # ((a b) (b a) (a c) (c a) (b c) (c b))

【讨论】:

  • 我喜欢 [*;*] 将列表“展平”的技巧!不过,我不喜欢 sigil-less 变量,对于我们这些确实了解 Perl(5 或 6)的人来说,这非常不太清楚。
  • @Larry 的speculation/specification of multidimensional arrays 读起来很有趣。它的一些更简单的部分,比如这个“技巧”,已经在 v6.c 和 Rakudo Perl 6 编译器中实现了。
【解决方案2】:

最终,您构建列表的方式一开始就错误。您可以像这样将您的排列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)[*;*]

【讨论】:

  • 谢谢,这确实是实现我想要的更好的方法。不过,我并没有将此标记为最佳答案,因为严格来说,这并不是我所问问题的答案。 :)
【解决方案3】:
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 时对其进行解构。长列表上的地图可能需要很长时间。

【讨论】:

  • 谢谢,.Slip 是我需要的技巧。太糟糕了».Slip 似乎不起作用......
【解决方案4】:

根据需要插入slips,例如通过

<a b c>.combinations(2).map(*.permutations.Slip).Array

[ slip .permutations for <a b c>.combinations(2) ]

如果您可以使用Seq,则无需在第一个示例中调用.Array,如果不需要可变性,则可以调用.list.cache(由PositionalBindFailover 提供)替换.

在第二个示例中,可以使用前缀 | 运算符代替 slip 子运算符。

【讨论】:

  • ».map 不等效。前者是自动线程的候选者。创建一个低一级的英雄联盟可能不是他想要的。
  • @gfldex:如果您愿意,您可以随时拨打.hyper 电话;另请注意,在您的示例中,组合列表被迭代两次
  • 谢谢,.Slip 是我需要的技巧。太糟糕了».Slip 似乎不起作用......
  • @mscha: 超算子下降到嵌套结构中,所以你正在滑动单元素叶子,这是一个 noop
  • @Christoph,我认为这不是真的,否则 ».permutations 部分也不会起作用。
猜你喜欢
  • 2019-12-12
  • 2013-04-24
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-19
相关资源
最近更新 更多