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

如何在Python字典中提取指定键对应值的重复咖啡名称?

提取字典两个键对应值中的重复咖啡名称

要解决这个需求,核心是找出两个键对应咖啡列表的共同元素,而非判断整个值列表是否完全相同。以下是两种实用的实现方式:

方法1:用集合快速求交集(自动去重,效率高)

集合的交集操作能直接筛选出两个列表都存在的元素,适合不需要保留重复项和顺序的场景:

def get_common_coffees(responses, key1, key2):
    # 校验输入的键是否有效且不同
    if key1 not in responses or key2 not in responses or key1 == key2:
        return []
    
    # 转集合后求交集,再转回列表
    coffee_set1 = set(responses[key1])
    coffee_set2 = set(responses[key2])
    return list(coffee_set1 & coffee_set2)

# 测试示例
responses = {
    "chocolate": ["摩卡", "热巧克力", "可可拿铁", "焦糖玛奇朵"],
    "medium": ["美式", "拿铁", "摩卡", "焦糖玛奇朵", "馥芮白"]
}

# 调用函数
print(get_common_coffees(responses, "chocolate", "medium"))
# 输出示例:['摩卡', '焦糖玛奇朵'](集合无序,顺序可能有差异)

方法2:用列表推导式保留顺序与重复项

如果需要保留原列表中的元素顺序,以及单个列表内的重复共同元素,用列表推导式实现:

def get_common_coffees_with_order(responses, key1, key2):
    if key1 not in responses or key2 not in responses or key1 == key2:
        return []
    
    coffee_list1 = responses[key1]
    coffee_list2 = responses[key2]
    # 遍历第一个列表,筛选出同时存在于第二个列表的元素
    return [coffee for coffee in coffee_list1 if coffee in coffee_list2]

# 测试示例
responses = {
    "chocolate": ["摩卡", "热巧克力", "摩卡", "焦糖玛奇朵"],
    "medium": ["美式", "拿铁", "摩卡", "焦糖玛奇朵", "馥芮白"]
}

print(get_common_coffees_with_order(responses, "chocolate", "medium"))
# 输出:['摩卡', '摩卡', '焦糖玛奇朵']

关键说明

  • 方法1利用集合的O(1)查找特性,处理大列表时效率远高于直接遍历;
  • 方法2完全保留原列表的顺序和重复元素,适合需要严格匹配原始数据结构的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:45:53