我是编程新手。我创建了一个在其初始化程序中使用列表理解的类。如下:
class Collection_of_word_counts():
'''this class has one instance variable, called counts which stores a
dictionary where the keys are words and the values are their occurences'''
def __init__(self:'Collection_of_words', file_name: str) -> None:
''' this initializer will read in the words from the file,
and store them in self.counts'''
l_words = open(file_name).read().split()
s_words = set(l_words)
self.counts = dict([ [word, l_words.count(word)]
for word
in s_words])
我认为我对新手来说做得还不错。有用!但我不完全理解这将如何在 for 循环中表示。我的猜测大错特错:
self.counts =[]
for word in s_words:
self.counts = [word, l_words.count(word)]
dict(self.counts)
最佳答案
这就是您对 for
循环的理解:
dictlist = []
for word in s_words:
dictlist.append([word, l_words.count(word)])
self.counts = dict(dictlist)
关于python - 理解列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21560404/