我有一个需要大量单词的循环,将每个单词分解为字母并将它们附加到一个大列表中。减少循环的运行时间并提高效率
然后我检查出现最信,如果未出现在字符串中,我把它存储在具有两个空间的列表:
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]
这可能是http://codereview.stackexchange.com/ – Blorgbeard
更好的候选人,当你移到codereview时,他们会要求查看你对该代码运行的分析器的输出。 –
看起来像['collections.Counter']的工作(https://docs.python.org/3.5/library/collections.html#collections.Counter)。 – bereal