我有一個需要大量單詞的循環,將每個單詞分解爲字母並將它們附加到一個大列表中。減少循環的運行時間並提高效率
然後我檢查出現最信,如果未出現在字符串中,我把它存儲在具有兩個空間的列表:
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