如何使用Python统计列表中字符串的最大出现次数
现有代码存在的问题
- 元素清洗逻辑无效:循环中给临时变量
item执行rstrip(),但没有修改原items列表的内容,清洗操作完全不生效 - 统计逻辑错误:使用
input_string.count(i)统计次数时,会把字符串中包含的子串也计入统计,比如拆分前的字符串是"apple, pineapple",统计apple的次数会得到2,和实际拆分后的元素出现次数不符 - 性能低下:两次遍历
items,且每次遍历都对整个字符串执行count操作,时间复杂度达到O(n²),列表长度变大后性能会非常差 - 变量命名不规范:使用Python内置函数名
max作为自定义变量,会覆盖内置的max()方法,后续代码调用max()会出现异常 - 返回结果结构不合理:会重复添加最高频元素和对应次数,比如两个元素都是最高频的场景下,返回结果为
['a',3,'b',3],不符合常规使用预期
正确实现方案
最优方案(使用Python标准库Counter)
collections.Counter是Python专门用来做可迭代对象频次统计的工具,代码简洁且性能稳定:
from collections import Counter def count_max_occurrences(input_str, split_sep=", "): # 拆分字符串并完成元素清洗 items = [item.rstrip() for item in input_str.split(split_sep)] # 统计所有元素的出现次数 count_res = Counter(items) # 得到最大出现次数 max_count = max(count_res.values()) # 收集所有达到最大次数的元素 max_items = [item for item, cnt in count_res.items() if cnt == max_count] # 返回结构可按需调整,这里返回(最高频元素列表,最大出现次数) return max_items, max_count # 测试用例 test_input = "苹果, 香蕉, 苹果, 橙子, 香蕉, 苹果" print(count_max_occurrences(test_input)) # 输出:(['苹果'], 3)
手动实现版本(不依赖标准库)
如果需要自己手写统计逻辑,一次遍历完成频次统计即可:
def count_max_occurrences(input_str, split_sep=", "): items = [item.rstrip() for item in input_str.split(split_sep)] count_dict = {} # 一次遍历完成所有元素的频次统计 for item in items: count_dict[item] = count_dict.get(item, 0) + 1 # 获取最大出现次数 max_count = max(count_dict.values()) # 收集最高频元素 max_items = [k for k, v in count_dict.items() if v == max_count] return max_items, max_count
内容的提问来源于stack exchange,提问作者Pooja Arora
相关产品推荐
相关产品推荐

