有没有一种方法可以解压缩嵌套冗余列表的列表?

时间:2020-07-29 16:33:58

标签: python-3.x list-manipulation

我有此列表:

input = [[[1,2]], [[3,4]], [[5,6]]]

想要的输出:

output = [[1,3,5],[2,4,6]]

我已经尝试过了:

x, y = map(list,zip(*input))

后来意识到这种方法由于多余的方括号而无法使用, 有没有一种方法可以解决这个问题而无需迭代。

2 个答案:

答案 0 :(得分:2)

In [117]: input = [[[1,2]], [[3,4]], [[5,6]]]

In [118]: list(zip(*[i[0] for i in input]))
Out[118]: [(1, 3, 5), (2, 4, 6)]

In [119]: list(map(list, zip(*[i[0] for i in input])))
Out[119]: [[1, 3, 5], [2, 4, 6]]

答案 1 :(得分:2)

您可以尝试以下方法:

>>> from operator import itemgetter
>>> input = [[[1,2]], [[3,4]], [[5,6]]]
>>> list(zip(*map(itemgetter(0), input)))
[(1, 3, 5), (2, 4, 6)]