【问题标题】:Understanding list comprehension理解列表理解
【发布时间】: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


【解决方案1】:

这就是你对 for 循环的理解:

dictlist = []
for word in s_words:
    dictlist.append([word, l_words.count(word)])
self.counts = dict(dictlist)

【讨论】:

    【解决方案2】:

    你的猜测完全没有错;您只是忘记附加并分配回self.counts

    counts = [] 
    for word in s_words:
        counts.append([word, l_words.count(word)])
    self.counts = dict(counts)
    

    本质上,这就是列表推导所做的;从循环表达式构建一个列表。

    您也可以将其转换为字典理解:

    self.counts = {word: l_words.count(word) for word in s_words}
    

    或者更好的是,使用collections.Counter() object 并省去所有工作:

    from collections import Counter
    
    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'''
        with open(file_name) as infile:
            self.counts = Counter(infile.read().split())
    

    Counter() 对象可以更有效地计算您的单词,并为您提供其他有用的功能,例如列出前 N 个计数和合并计数的能力。

    【讨论】:

    • 在你得到 -1 之前删除它:D
    【解决方案3】:

    您实际上是在创建一个字典,其中字典的键是单词,与该键对应的值是单词出现的次数。

    self.counts ={}
    
    for word in s_words:
       self.counts[word] = l_words.count(word)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多