多列表重复值统计:Counter()转换与自定义计数需求
解决方案:多列表值统计与筛选
实现思路
- 为每个子列表生成元素出现次数的
Counter,快速查询元素在单列表内的出现次数; - 收集所有子列表中的唯一元素,逐个统计两个核心指标:
- 元素出现的列表数量:统计包含该元素的子列表总数;
- 元素在各列表中出现次数的最小值:提取该元素在所有包含它的子列表中的出现次数,取最小值;
- 筛选出「在≥2个列表中出现,但未在所有列表中出现」的元素,整理输出结果。
代码实现
from collections import Counter # 示例主列表(可动态添加子列表) main_list = [ ['Limerick (IRE)', 'Fairyhouse (IRE)', 'Gowran Park (IRE)', 'Galway (IRE)', 'Roscommon (IRE)', 'Ballinrobe (IRE)', 'Roscommon (IRE)', 'Downpatrick (IRE)', 'Ballinrobe (IRE)', 'Curragh (IRE)', 'Naas (IRE)', 'Curragh (IRE)', 'Galway (IRE)', 'Cork (IRE)', 'Punchestown (IRE)', 'Galway (IRE)', 'Tipperary (IRE)', 'Curragh (IRE)', 'Gowran Park (IRE)', 'Cork (IRE)', 'Galway (IRE)', 'Killarney (IRE)', 'Curragh (IRE)', 'Roscommon (IRE)', 'Limerick (IRE)', 'Newton Abbot', 'Bangor-on-Dee', 'Bangor-on-Dee'], ['Newton Abbot', 'Worcester', 'Ffos Las', 'Worcester', 'Newton Abbot', 'Hereford', 'Worcester', 'Chepstow', 'Newton Abbot', 'Bangor-on-Dee', 'Stratford', 'Ffos Las', 'Huntingdon', 'Newton Abbot', 'Bangor-on-Dee'], ['Aintree', 'Market Rasen', 'Market Rasen', 'Newcastle', 'Stratford', 'Hexham', 'Cartmel', 'Stratford', 'Cartmel', 'Cartmel','Bangor-on-Dee', 'Stratford', 'Ffos Las', 'Huntingdon', 'Newton Abbot', 'Bangor-on-Dee', 'Killarney (IRE)'] ] # 为每个子列表生成Counter list_counters = [Counter(sublist) for sublist in main_list] total_lists = len(main_list) # 收集所有唯一元素 all_elements = set() for sublist in main_list: all_elements.update(sublist) # 统计并筛选符合条件的元素 result = {} for elem in all_elements: # 统计出现的列表数量 list_count = sum(1 for cnt in list_counters if elem in cnt) if list_count < 2 or list_count == total_lists: continue # 跳过仅在1个列表出现,或在所有列表出现的元素 # 统计各列表中出现次数的最小值 min_count = min(cnt[elem] for cnt in list_counters if elem in cnt) result[elem] = (list_count, min_count) # 输出结果 for elem, stats in result.items(): print(f"{elem}: {stats[0]}(仅出现在{stats[0]}个列表中),{stats[1]}(这些列表中至少出现{stats[1]}次)")
输出结果
Killarney (IRE): 2(仅出现在2个列表中),1(这些列表中至少出现1次) Stratford: 2(仅出现在2个列表中),1(这些列表中至少出现1次) Ffos Las: 2(仅出现在2个列表中),1(这些列表中至少出现1次) Huntingdon: 2(仅出现在2个列表中),1(这些列表中至少出现1次)
代码说明
list_counters:预先生成每个子列表的计数,避免重复调用count()方法,提升效率(尤其当列表数量多、元素量大时);- 筛选逻辑:直接跳过不符合条件的元素,减少无效计算;
- 适配可变列表数量:代码中
total_lists由main_list的长度动态获取,无论新增多少子列表都无需修改核心逻辑。
内容的提问来源于stack exchange,提问作者Phil
相关产品推荐
相关产品推荐

