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

Python筛选列表中冒号后子串存在于另一列表的元素

问题说明

现有如下两个列表:

x1 = ['Apples:Red',
      'Apples:Green',
      'Bananas:Yellow',
      'Grapes:Purple',
      'Grapes:Green']
x2 = ['Green', 'Yellow']

需要实现的逻辑:检查列表x1中各字符串冒号后的子串,是否与列表x2中的任意字符串匹配,筛选出所有符合条件的元素,期望输出结果如下:

['Apples:Green',
 'Bananas:Yellow',
 'Grapes:Green']
实现方案

直接通过列表推导即可完成筛选,提前将x2转为集合可以把查找的时间复杂度从O(n)降到O(1),数据量较大时性能优势非常明显:

x1 = ['Apples:Red',
      'Apples:Green',
      'Bananas:Yellow',
      'Grapes:Purple',
      'Grapes:Green']
x2 = ['Green', 'Yellow']

match_set = set(x2)
result = [item for item in x1 if item.split(':', 1)[1] in match_set]

代码中使用split(':', 1)是为了仅按第一个冒号做拆分,避免字符串内存在多个冒号时取错后缀的问题,运行后得到的result和期望输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 18:31:04