【发布时间】:2017-01-14 21:03:30
【问题描述】:
我有以下结构
a = [['a', 'b', 'c'], ['d', 'e', 'f'], [['g', 'h', 'i'], ['l', 'm', 'n']]]
我想获得以下内容:
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]
我尝试了以下方法:
a.flatten => ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'l', 'm', 'n']
a.flatten(1) => ['a', 'b', 'c', 'd', 'e', 'f', ['g', 'h', 'i'], ['l', 'm', 'n']]
我目前找到的解决方案是将初始结构更改为这种格式:
b = [[['a', 'b', 'c']], [['d', 'e', 'f']], [['g', 'h', 'i'], ['l', 'm', 'n']]]
然后调用
b.flatten(1) => [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]
但我可以这样做只是因为我能够更改 a 的构建方式。我的问题仍然存在:如何从a 开始获得我想要的结果?
【问题讨论】:
-
如果您知道您需要/拥有三元组(大小为 3 的数组),我会选择一个无法回答您问题的解决方案 :) 和
flatten然后切片。 -
不,每个数组里面的元素个数不固定,数组和子数组的个数也一样