扁平化双重嵌套列表
如何把这个:
[[[1,2,3], ['a','b','c']], [[4,5], ['d','e']], [[6,7,8,9], ['f','g','h','i']]]
转换成这个:
[[1,2,3,4,5,6,7,8,9], ['a','b','c','d','e','f','g','h','i']]
如果你会用Python的话,一定有办法可以用zip和列表推导式来实现。
1 个回答
3
这看起来是一个可以用zip和itertools.chain.from_iterable()来解决的任务。
data = [[[1,2,3], ['a','b','c']], [[4,5], ['d','e']], [[6,7,8,9], ['f','g','h','i']]]
list(zip(*data))
这样你就能得到
[([1, 2, 3], [4, 5], [6, 7, 8, 9]), (['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i'])]
现在对里面的列表使用chain.from_iterable
:
data = [[[1,2,3], ['a','b','c']], [[4,5], ['d','e']], [[6,7,8,9], ['f','g','h','i']]]
print([list(itertools.chain.from_iterable(inner)) for inner in zip(*data)])