首页 > 解决方案 > 转置子子列表中的元素

问题描述

我有以下列表:

geo=[
[ ['a'],     ['b','c']     ],
[ ['d','e'], ['f','g','h'] ],
[ ['i']                    ]
]

我的目标是获得一个子列表的列表:第一个子列表的元素在原始子子列表的第一个位置,第二个子列表的元素在第二个位置,第三个子列表的元素在第三个位置,依此类推......换句话说,我需要:

result=[
['a','b','d','f','i'],
['c','e','g'],
['h']
]

请记住,子列表中的元素数量可能会有所不同,并且子列表中的子列表数量也可能会有所不同。不幸的是,我不能使用 Pandas 或 Numpy。

使用zip和 Alex Martelli 的flatten lists方法,我已经能够获得一个包含 first 元素元组的列表,但我无法遍历其余元素。

result=zip(*[item for sublist in geo for item in sublist])
# [('a', 'b', 'd', 'f', 'i')]

这是我在过去 4 周内参与的项目所需要的最后一件事。我快完成了。非常感谢您提前。

标签: pythonlist

解决方案


您可以使用itertools.zip_longestizip_longest在 Python2 中):

import itertools
l = [[['a'], ['b', 'c']], [['d', 'e'], ['f', 'g', 'h']], [['i']]]
d= [list(filter(lambda x:x is not None, i)) for i in itertools.zip_longest(*[i for b in l for i in b])]
print(d)

输出:

[['a', 'b', 'd', 'f', 'i'], ['c', 'e', 'g'], ['h']]

推荐阅读