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

如何提取字典列表中不属于出现频率最高城市的客户名单

最优实现方案

以下实现时间复杂度为O(n),仅需遍历两次客户列表,无冗余计算,是性能最优的写法:

from collections import Counter

# 输入数据
customers = [{'customer': 'Charles', 'city': 'Paris'}, {'customer': 'John', 'city': 'New York'}, {'customer': 'Jean', 'city': 'Paris'}]

# 统计城市频次、取最高频城市
city_counts = Counter(c['city'] for c in customers)
most_common_city = city_counts.most_common(1)[0][0]

# 列表推导式过滤不符合要求的客户
result = [c['customer'] for c in customers if c['city'] != most_common_city]

示例输入下运行后result值为['John'],和预期一致。

如果存在多个城市出现频次相同且均为最高的场景,可以使用如下兼容写法,避免只匹配第一个最高频城市的问题:

from collections import Counter

customers = [{'customer': 'Charles', 'city': 'Paris'}, {'customer': 'John', 'city': 'New York'}, {'customer': 'Jean', 'city': 'Paris'}, {'customer': 'Amy', 'city': 'New York'}]

city_counts = Counter(c['city'] for c in customers)
# 取最高频次
max_count = max(city_counts.values())
# 收集所有最高频的城市
most_common_cities = {city for city, cnt in city_counts.items() if cnt == max_count}

# 过滤
result = [c['customer'] for c in customers if c['city'] not in most_common_cities]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:15:04