展平双重嵌套列表

时间:2014-07-14 10:45:05

标签: python list-comprehension nested-lists

如何转换:

[[[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和list comprehensions。

1 个答案:

答案 0 :(得分:3)

看起来像是zipitertools.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)])