python - 理解列表理解

标签 python for-loop list-comprehension

我是编程新手。我创建了一个在其初始化程序中使用列表理解的类。如下:

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/

相关文章:

Python - 使用 2 个 for 循环和一个 ADD AND 操作数来理解列表

Python Kivy 严重文本错误。无法找到任何有值(value)的文本提供者

java - 我尝试运行这段代码,它运行时不会抛出错误,问题是它不会执行 for 循环我只是一个初学者,所以请

python - 如何计算可迭代对象中的非空元素?

python - 将程序转换为列表理解

python - 如何在运行时更改工具栏中 Action 的图标?

python - 为什么更新类属性不会更新该类的所有实例?

batch-file - For循环批处理中的多个条件?

C++ Visual Studio-运算符重载中的空循环会导致调试错误?

haskell - 在 Haskell 中的并行列表推导式中使用变量