【发布时间】:2014-02-04 18:26:05
【问题描述】:
我对编程有点陌生。我创建了一个在其初始化程序中使用列表理解的类。如下:
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)
【问题讨论】:
标签: python for-loop list-comprehension