python - 我应该在这里使用哪种数据结构?

标签 python

这里是新程序员。目前,我的程序有一本字典,其中包含所有年份以及每年在文学中使用了多少个单词。

我现在需要做的是通过查找用户给出的特定词来找到所述年份的相对频率。相对频率的计算方法是将特定单词的使用次数除以当年使用的单词总数。

我是否需要制作另一本包含年份和该词在该年使用次数的词典?还是完全不同的数据结构?我还应该提到,用户提供了开始日期和结束日期。

下面是我目前拥有的字典的功能。如果您对如何改进它也有任何建议,我会洗耳恭听!

yearTotal = dict()
def addTotal():
    with open('total_counts.csv') as allWords:
        readW = csv.reader(allWords, delimiter=',')
        for row in readW:
            yearTotal[row[0]] = row[1]

addTotal()

最佳答案

我假设您没有很多年(可能最多几百年),所以我希望列表和字典具有相似的查找时间。然而,字典在语义上更方便。

同时,每年你可能有很多单词,所以最好使用具有常量 (O(1)) 查找的结构,所以 dict 就是这样。

from collections import defaultdict

yearTotal = defaultdict(labda: defaultdict(int))

fh = open('total_counts.csv')
for year, word in csv.reader(fh, delimiter=","):
    yearTotal[year][''] += 1  # here we'll cache the number of words
    yearTotal[year][word] += 1

# ...
word = "foo"
year = "1984"
relative_frequency = float(yearTotal[year][word]) / yearTotal[year]['']

关于python - 我应该在这里使用哪种数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40899153/

相关文章:

python - 无法从 github 或 pip 安装 python 模块 aubio

python - 加法和乘法的联合累加

python - 无法在 Jupyter Notebook 上运行 fastai 库

python - OpenCV python,如何以python方式将操作应用于单个 channel ?

python - “ImageDataGenerator”对象没有属性 'image_data_generator'

python - 如何在 Pandas DataFrame 中使用 inside/in 运算符?

python - Pandas 将值与具有过滤条件的前一行进行比较

python - 在python中如何计算特定参数之后传递的参数数量?

python - 查找自上次事件 Pandas 数据框以来的天数

python - Cython 没有速度提升