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

如何基于双层嵌套列表与布尔列表构建三级嵌套列表?

搞定三级嵌套列表的构造问题

嘿,我看你在组合双层嵌套列表和布尔值列表成三级嵌套结构的时候遇到了小麻烦,咱们一步步来解决它!

问题回顾

你手头有两个列表:

  • 双层嵌套的lst,每个元素都是单元素子列表
  • 普通的布尔值列表booleanList
    你想要把它们组合成**每个元素都是[双层子列表, 布尔值单元素列表]**的三级嵌套结构,但当前代码的输出和预期不符。

你的现有代码

lst = [["Family=252.007 - SE.540x540"], ["Family=252.001 - SE.540x540"], ["Family=252.025 - SE.540x540"]]
booleanList = [True, True, False]
newList = [list(i) for i in zip(lst, booleanList)]
print(newList)

当前输出(不符合预期)

[[['Family=252.007 - SE.540x540'], True], [['Family=252.001 - SE.540x540'], True], [['Family=252.025 - SE.540x540'], False]]

预期输出

[[["Family=252.007 - SE.540x540"], [True]],[["Family=252.001 - SE.540x540"],[True]], [["Family=252.025 - SE.540x540"], [False]]]

问题根源

核心问题很简单:你用zip把lst的子列表和booleanList里的单个布尔值直接配对了,但预期里需要把每个布尔值再包裹一层列表(也就是[True]而不是True)。zip本身只是做元素配对,不会自动帮你嵌套一层结构,所以才会出现当前的结果。

两种简洁的解决方案

方案1:先转换布尔值列表,再打包

先把booleanList里的每个元素都变成单元素列表,再和lst做zip操作,逻辑更直观:

lst = [["Family=252.007 - SE.540x540"], ["Family=252.001 - SE.540x540"], ["Family=252.025 - SE.540x540"]]
booleanList = [True, True, False]

# 把每个布尔值包裹成单元素列表
boolean_nested = [[b] for b in booleanList]
# 打包后转成目标列表
newList = [list(item) for item in zip(lst, boolean_nested)]

print(newList)

方案2:列表推导式一步到位

更紧凑的写法,直接在推导式里处理布尔值的嵌套,少写一行代码:

lst = [["Family=252.007 - SE.540x540"], ["Family=252.001 - SE.540x540"], ["Family=252.025 - SE.540x540"]]
booleanList = [True, True, False]

newList = [[sub_list, [b]] for sub_list, b in zip(lst, booleanList)]

print(newList)

验证结果

两种方案都会输出你想要的三级嵌套列表结构,完全符合预期!

内容的提问来源于stack exchange,提问作者Math

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:14:50