You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按索引合并包含字符串、布尔值的三个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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:45:34