【发布时间】:2017-04-21 16:24:47
【问题描述】:
我有一个循环,它需要大量的单词,将每个单词分解成字母并将它们附加到一个大列表中。
然后我检查出现次数最多的字母,如果它还没有出现在字符串中,我会将它存储在一个有两个空格的列表中:
list[0] = 出现次数最多的字母
list[1] = 发生了多少次
这个循环非常低效。它可以工作,但返回值大约需要 25-30 秒。在此之前它会继续运行并且不会返回任何值。
如何提高我编写的代码的效率?
def choose_letter(words, pattern):
list_of_letters = []
first_letter = [] # first spot is the letter, second is how many times it appears
second_letter =[] # first spot is letter, second how many times it appears
max_appearances = ["letter", 0]
for i in range(len(words)): # splits up every word into letters
list_of_letters.append(list(words[i]))
list_of_letters = sum(list_of_letters, []) # concatenates the lists within the list
first_letter = list_of_letters.count(0)
for j in list_of_letters:
second_letter = list_of_letters.count(j)
if second_letter >= max_appearances[1] and j not in pattern:
max_appearances[0] = j
max_appearances[1] = second_letter
else:
list_of_letters.remove(j)
return max_appearances[0]
【问题讨论】:
-
当您转到 codereview 时,他们会要求查看您针对此代码运行的分析器的输出。
-
看起来像是
collections.Counter的工作。 -
无论你做什么,我相信你会从使用字典而不是列表来存储你的计数中获益良多。所以
dict、defaultdict或上面提到的collections.Counter。
标签: python performance loops processing-efficiency