如何按索引合并包含字符串、布尔值的三个Python列表?
按索引合并多列表为嵌套列表
需求:将三个包含不同类型元素的Python列表,按对应索引合并成嵌套列表,最终结构示例如下:[["Ainsley", "Small", True], ["Ben", "Large", False], ["Chani", "Medium", True], ["Depak", "Medium", False]]
原始代码如下:
first_names = ["Ainsley", "Ben", "Chani", "Depak"] preferred_size = ["Small", "Large", "Medium"] preferred_size.append("Medium") expedited_shipping = [True, False, True, False]
解决方案
有两种简洁的实现方式:
方式1:通过索引遍历生成
利用列表推导式,遍历列表的索引位置,依次从三个列表中取出对应元素组成子列表:
merged_list = [[first_names[i], preferred_size[i], expedited_shipping[i]] for i in range(len(first_names))] print(merged_list)
方式2:使用zip()函数批量配对
zip()函数会自动将多个列表中同索引的元素配对成元组,再通过map()将元组转为列表,最后转成列表即可得到嵌套结构:
merged_list = list(map(list, zip(first_names, preferred_size, expedited_shipping))) print(merged_list)
两种方法最终输出结果一致:
[["Ainsley", "Small", True], ["Ben", "Large", False], ["Chani", "Medium", True], ["Depak", "Medium", False]]
内容的提问来源于stack exchange,提问作者Sharry
相关产品推荐
相关产品推荐

