假设我们正在解决一个简单的单词计数问题。有一个列表,我们正在尝试找到列表中每个单词出现的次数。在此情况下哪种模式更快?
book_title = ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gasby','hamlet','adventures','of','huckleberry','fin']
word_count_dict = {}
模式 1
for word in book_title:
if word in word_count_dict:
word_count_dict[word] += 1
else:
word_count_dict[word] = 1
模式 2
for word in book_title:
if word not in word_counter:
word_counter[word] = 1
else:
word_counter[word] += 1