我试图在23万字的列表上计算重复的单词.我使用python字典这样做.代码如下:
for words in word_list:
if words in word_dict.keys():
word_dict[words] += 1
else:
word_dict[words] = 1
Run Code Online (Sandbox Code Playgroud)
上面的代码用了3分钟!我运行相同的代码超过150万字,它运行超过25分钟,我失去了耐心并终止.后来我发现,我可以使用从下面的代码在这里(如下所示).结果是如此令人惊讶,它在几秒钟内完成!所以我的问题是什么是更快的方式来做这个操作?我想字典创建过程必须花费O(N)时间.Counter方法如何能够在几秒钟内完成此过程,并创建一个精确的单词词典作为键和频率的值?
from collections import Counter
word_dict = Counter(word_list)
Run Code Online (Sandbox Code Playgroud) 使用字典计算输入字符串中字母出现的频率。只应计算字母,而不是空格、数字或标点符号。大写字母应被视为与小写字母相同。例如,count_letters("This is a sentence.") 应该返回 {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
def count_letters(text):
result = {}
# Go through each letter in the text
for letter in text:
# Check if the letter needs to be counted or not
if letter not in result:
result[letter.lower()] = 1
# Add or increment the value in the dictionary
else:
result[letter.lower()] += 1
return result
print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, …Run Code Online (Sandbox Code Playgroud) 我正在尝试从列表中生成字典
names = ['tango', 'bravo', 'tango', 'alpha', 'alpha']
Run Code Online (Sandbox Code Playgroud)
结果应该看起来像这样:
{'tango': 2 , 'bravo': 1 , 'alpha': 2}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
我有以下列表:
pet = ['cat','dog','fish','cat','fish','fish']
Run Code Online (Sandbox Code Playgroud)
我需要将它转换为这样的字典:
number_pets= {'cat':2, 'dog':1, 'fish':3}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?