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

如何优化无外部导入的字符串列表各位置高频字符查找代码

问题:找出字符串列表各位置出现次数最多的字符

我有一个字符串列表,示例如下:

words = ["test", "secondTest", "thirdTest"]

需要找出列表中每个位置上出现次数最多的字符——比如第一个位置出现最多的是't',第二个是'e',以此类推。

当前实现的函数处理长列表时耗时过长:之前用max()单行代码效率更低,换成字典计数后仍需进一步优化,要求不能使用任何外部导入。

以下是当前的函数实现:

def mostFrequent(lst: list[str]) -> str:
    dic = {}
    count, itm = 0, ''
    for item in reversed(sorted(lst)):
        dic[item] = dic.get(item, 0) + 1
        if dic[item] >= count:
            count, itm = dic[item], item
    return (itm)


def most_frequent_chars() -> str:
    words = ["test", "secondTest", "thirdTest"]
    maxOccurs = ""
    listOfChars = []
    for i in range(len(max(words, key=len))):
        for item in words:
            try:
                listOfChars.append(item[i])
            except IndexError:
                pass

        maxOccurs += mostFrequent(listOfChars)
        listOfChars.clear()
    return maxOccurs

优化方案

代码优化点分析

当前实现存在几个效率瓶颈:

  1. mostFrequent函数中对字符列表先排序再遍历,排序的时间复杂度为O(n log n),属于没必要的额外开销;
  2. 每次循环都先收集所有位置的字符到列表再统计,增加了内存占用和列表操作的时间;
  3. 用try-except捕获索引错误,异常捕获的性能开销远大于直接的条件判断;
  4. 字符串拼接使用+=,由于字符串是不可变类型,每次拼接都会生成新字符串,长列表下效率极低。

优化后的代码

def most_frequent_chars() -> str:
    words = ["test", "secondTest", "thirdTest"]
    max_len = max(len(word) for word in words)
    result = []
    
    for i in range(max_len):
        char_count = {}
        max_count = 0
        most_char = ''
        for word in words:
            # 直接跳过长度不足的单词,替代异常捕获
            if i >= len(word):
                continue
            char = word[i]
            char_count[char] = char_count.get(char, 0) + 1
            # 保持原逻辑:次数相同选字典序最小的字符
            if char_count[char] > max_count or (char_count[char] == max_count and char < most_char):
                max_count = char_count[char]
                most_char = char
        result.append(most_char)
    
    # 用列表join拼接结果,比字符串+=效率高
    return ''.join(result)

优化效果说明

  1. 去掉排序操作:直接遍历统计字符出现次数,时间复杂度从O(n log n)降至O(n);
  2. 合并统计逻辑:将字符统计直接融入主循环,避免函数调用的额外开销,同时省去字符列表的收集步骤;
  3. 替换异常捕获:用if i >= len(word)直接判断,大幅降低性能开销;
  4. 优化字符串拼接:用列表append存储结果,最后通过join生成最终字符串,避免多次生成新字符串的开销。

运行优化后的代码,结果与原代码完全一致,但处理长列表时的执行效率能提升数倍。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:30:57