如何使循环计算更快

How to make loop calculate faster

我想让这段代码计算得更快。我的代码有太多循环,我想减少它。如何最小化 for 循环和 while 循环。我的代码是要划分英文单词,出现在字符串(String)文本中,3个字符,统计三组字符出现的频率。该函数的值为 dict,其中键是文本中的一组三个字符,值是该字符在键中出现的频率。必须是单词,如果长度小于3,则频率计数不区分大小写('ant'和'Ant'是cadia)。字符必须定义为键,例如'a','in'.

def main():
    text = "Thank you for help me"
    print(three_letters_count(text))


def three_letters_count(text):
    d = dict()
    res = []
    li = list(text.lower().split())
    for i in li:
        if len(i) < 3:
            res.append(i)  
        while len(i) >= 3: 
            res.append(i[:3])  
            i = i[1:]
    
    for i in res:
        d[i] = res.count(i)
        
    return d
    
    



if __name__ == '__main__':
    main()

您可以调整 while 外观并将其切换为 for 循环。

查看下面调整后的函数。

def three_letters_count(text):
    d = dict()
    res = []
    li = list(text.lower().split())
    for i in li:
        if len(i) < 3:
            res.append(i)  
        for index in range(0, len(i)):
            three_letter = i[index:index+3]
            if(len(three_letter) >= 3):
                res.append(three_letter)
    
    for i in res:
        d[i] = res.count(i)
        
    return d

正如所承诺的,只是已接受答案的替代方案:

def main():
    text = "Thank you for help me thank you really so much"
    print(three_letters_count(text))


def three_letters_count(text):
    d = dict()
    res = {}
    li = list(text.lower().split())
    for i in li:
        if len(i) < 3:
            if (i in res):
                res[i] = res[i] + 1
            else:
                res[i] = 1  
        startpos = 0
        for startpos in range(0, len(i)):
            chunk = i[startpos:startpos + 3]
            if (chunk in res):
                res[chunk] = res[chunk] + 1
            else:
                res[chunk] = 1

    return res

if __name__ == '__main__':
    main()

它产生(修改后的输入):

{'tha': 2, 'han': 2, 'ank': 2, 'you': 2, 'for': 1, 'hel': 1, 'elp': 1, 'me': 1, 'rea': 1, 'eal': 1, 'all': 1, 'lly': 1, 'so': 1, 'muc': 1, 'uch': 1}