python - 转置子子列表中的元素
问题描述
我有以下列表:
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 周内参与的项目所需要的最后一件事。我快完成了。非常感谢您提前。
解决方案
您可以使用itertools.zip_longest
(izip_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']]
推荐阅读
- python - Client = discord.client() TypeError: 'module' object is not callable
- stata - 在 coefplot 中分配不同的标签
- php - 使用 OOP PHP 的 Ajax 请求
- java - 如何撤消任何功能
- javafx - 如何获取用户点击java fx的x和y
- javascript - 如何在 javascript 中获取这种特定的日期时间格式
- c++ - Rcpp,使函数可以从 DLL 中用于 R
- html - 如何让我的“查看更多”(“seemorelink”)链接更靠近我的图像?
- angular - 以角度 6 反应形式处理数字输入类型,例如电话或时间?
- java - 如何在 Java 中实现 Graphic2D 对象的颜色变化?