【发布时间】:2021-08-03 12:22:31
【问题描述】:
我想知道如何完全扁平化列表和包含它们的事物。除其他外,我想出了一个解决方案,将具有多个元素的东西滑倒并将它们放回原处,或者在滑倒后将具有一个元素的东西拿走。
这与How do I “flatten” a list of lists in perl 6? 有点不同,后者并不完全平坦,因为任务是重组。
但是,也许有更好的方法。
my @a = 'a', ('b', 'c' );
my @b = ('d',), 'e', 'f', @a;
my @c = 'x', $( 'y', 'z' ), 'w';
my @ab = @a, @b, @c;
say "ab: ", @ab;
my @f = @ab;
@f = gather {
while @f {
@f[0].elems == 1 ??
take @f.shift.Slip
!!
@f.unshift( @f.shift.Slip )
}
}
say "f: ", @f;
这给出了:
ab: [[a (b c)] [(d) e f [a (b c)]] [x (y z) w]]
f: [a b c d e f a b c x y z w]
奇怪的是,我还阅读了一些 python 答案:
- Making a flat list out of list of lists in Python
- How flatten a list of lists one step
- flatten list of lists of lists to a list of lists
itertools.chain(*sublist) 看起来很有趣,但答案要么是递归的,要么是硬编码的两个级别。函数式语言在源代码中是递归的,但我预料到了。
【问题讨论】: