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

如何根据字典条件动态合并指定Python列表为单个列表

需求说明

现有若干列表:

List_1 = ['x1', 'y1', 'z1']
List_2 = ['x2', 'y2', 'z2']
List_3 = ['x3', 'y3', 'z3']
...
List_n = ['xn', 'yn', 'zn']

原本计划用字典指定哪些列表需要合并,写法如下:

list_dict = {List_1: 'yes', List_2: 'yes', List_3: 'no', ..., List_n: 'yes'}

但由于无法将列表对象作为字典键,因此改为以列表变量名的字符串作为键:

list_dict = {'List_1': 'yes', 'List_2': 'yes', 'List_3': 'no', ..., 'List_n': 'yes'}

需要实现:根据list_dict中的标记,将所有对应值为'yes'的列表(例如List_1、List_2、List_n,排除List_3)合并为一个最终列表:

Final_List = ['x1', 'y1', 'z1', 'x2', 'y2', 'z2', ...., 'xn', 'yn', 'zn']

实现要求:

  • 优先使用列表推导式或lambda函数完成
  • 需解决通过字符串键动态访问对应列表变量的问题(可借助globals()方法)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:40:43