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

如何从两个字符串列表中获取大小写不敏感的非公共元素?

问题描述

给定两个列表:

first = ['A' , 'B' , 'c' , 'd']
second = ['a' , 'b', 'e']

需要获取大小写不敏感的两个列表非公共元素,期望结果为 ['c' , 'd' ,'e']。

原尝试的代码如下,但无法处理大小写不敏感的场景:

a, b = list(set(a) - set(b)), list(set(b) - set(a))
print("list1 : ", a)
print("list2 : ", b)
问题原因

原代码直接使用集合的差集运算,但集合默认是区分大小写的,因此'A'和'a'会被判定为不同元素,无法满足需求。

解决方案

核心思路是:先通过统一大小写判断元素是否为公共元素,再保留原列表中元素的原始大小写,筛选出非公共元素。

实现代码如下:

first = ['A' , 'B' , 'c' , 'd']
second = ['a' , 'b', 'e']

# 将两个列表的元素转为小写,生成集合用于判断公共性
lower_first = {item.lower() for item in first}
lower_second = {item.lower() for item in second}

# 找出所有非公共元素的小写形式
non_common_lower = (lower_first - lower_second) | (lower_second - lower_first)

# 从原列表中筛选出符合条件的元素(保留原始大小写)
result = []
for item in first:
    if item.lower() in non_common_lower:
        result.append(item)
for item in second:
    if item.lower() in non_common_lower:
        result.append(item)

print(result)  # 输出: ['c', 'd', 'e']

代码说明

  1. 先将两个列表的元素转为小写并生成集合,这样可以忽略大小写判断元素是否重复。
  2. 通过集合的并集运算,得到所有非公共元素的小写形式集合。
  3. 遍历原列表,收集那些转小写后属于非公共集合的元素,保留原始大小写。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:45:20