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

Python中如何根据布尔列表cond1筛选sol1对应False的元素

提取列表中对应布尔列表False位置的元素

需求:给定两个列表sol1和cond1,提取sol1中与cond1里False值所在索引对应的元素。

示例输入:

sol1 = [1, 2, 4, 6, 7]
cond1 = [False, True, False, True, True]

预期输出:

[1, 4]

解决方案

方法1:列表推导式 + zip(推荐)

利用zip将两个列表的元素一一配对,筛选出cond1元素为False时对应的sol1元素:

sol1 = [1, 2, 4, 6, 7]
cond1 = [False, True, False, True, True]

result = [s for s, c in zip(sol1, cond1) if not c]
print(result)

方法2:通过索引遍历

遍历列表索引,检查cond1对应位置的值,提取符合条件的sol1元素:

result = [sol1[i] for i in range(len(sol1)) if not cond1[i]]

注意事项

  • 确保两个列表长度一致,否则zip会以较短列表的长度为准,超出部分元素会被忽略;若长度不一致,需先做长度校验或处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:05:27