如何提取字典列表中不属于出现频率最高城市的客户名单
最优实现方案
以下实现时间复杂度为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
相关产品推荐
相关产品推荐

