Python - 迭代列表元组列表的方法
pythonserver side programmingprogramming更新于 2025/9/17 9:48:17
列表是一个重要的容器,几乎用于日常编程以及 Web 开发的所有代码中,使用得越多,掌握它的要求就越高,因此了解它的操作是必要的。
示例
# 使用 itertools.ziplongest
# 导入库
from itertools import zip_longest
# 初始化 listoflist
test_list = [
[('11'), ('12'), ('13')],
[('21'), ('22'), ('23')],
[('31'), ('32'), ('33')]
]
# 打印初始列表
print ("Initial List = ", test_list)
# 将列表元组列表迭代为单个列表
res_list = [item for my_list in zip_longest(*test_list)
for item in my_list if item]
# 打印最终列表
print ("Resultant List = ", res_list)
# 使用 itertools.ziplongest + lambda + chain
# 导入库
from itertools import zip_longest, chain
# 初始化列表列表
test_list = [
[('11'), ('12'), ('13')],
[('21'), ('22'), ('23')],
[('31'), ('32'), ('33')]
]
# 打印初始列表
print ("Initial List = ", test_list)
# 将列表元组列表迭代为单个列表
# 使用 lambda + chain + filter
res_list = list(filter(lambda x: x, chain(*zip_longest(*test_list))))
# 打印最终列表
print ("Resultant List = ", res_list)
# 使用列表推导的列表
# 初始化列表列表
test_list = [
[('11'), ('12'), ('13')],
[('21'), ('22'), ('23')],
[('31'), ('32'), ('33')]
]
# 打印初始列表
print ("Initial List = ", test_list)
# 将列表元组列表迭代为单个列表
# 使用列表推导式
res_list = [item for list2 in test_list for item in list2]
# 打印最终列表
print ("Resultant List = ", res_list)
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

