【问题标题】:Python- Count each letter in a list of wordsPython-计算单词列表中的每个字母
【发布时间】:2011-09-15 05:35:58
【问题描述】:

所以我有一个单词列表“wordList = list()。”现在,我正在使用此代码计算整个列表中每个单词中的每个字母

cnt = Counter()
for words in wordList:
      for letters in words:
          cnt[letters]+=1

但是,我希望它以不同的方式计算。我希望该函数从列表中的所有单词中找到最常见的字母,但只能通过计算每个单词的每个字母一次(忽略某些单词可以有同一个字母的多个副本的事实)。

例如,如果列表包含“happy, harpy and hasty”,则happy 中的两个p 应该只计算一次。所以该函数应该返回一个频率最高的字母列表(按顺序),而不需要重复计算。在上述情况下,它将是 'h, a, p, y, r, s"

【问题讨论】:

  • 在您的示例中,y 是 3 个单词,但 p 仅在 2 个单词中,所以结果应该在 p 之前有 y。

标签: python algorithm collections dictionary


【解决方案1】:
cnt = Counter()
for words in wordList:
      for letters in set(words):
          cnt[letters]+=1

【讨论】:

    【解决方案2】:

    添加set 电话:

    cnt = Counter()
    for word in wordList:
          for letter in set(word):
              cnt[letter]+=1
    

    【讨论】:

      【解决方案3】:
      cnt = Counter()
      for word in wordList:
          lSet = set(word)
          for letter in lSet:
              cnt[letter] +=1             
      

      【讨论】:

        【解决方案4】:

        您可以用update 消除for,它会更新可迭代对象(在本例中为字符串)的计数:

        from collections import Counter
        words = 'happy harpy hasty'.split()
        c=Counter()
        for word in words:
            c.update(set(word))
        print c.most_common()
        print [a[0] for a in c.most_common()]
        

        [('a', 3), ('h', 3), ('y', 3), ('p', 2), ('s', 1), ('r', 1), ('t', 1)]
        ['a', 'h', 'y', 'p', 's', 'r', 't']
        

        【讨论】:

          【解决方案5】:

          itertools 中使用迭代器组合器的另一种方法:

          import collections
          import itertools
          
          cnt = collections.Counter(itertools.chain.from_iterable(itertools.imap(set, wordList)))
          

          【讨论】:

          • 你真的应该使用chain.from_iterable,否则*arg扩展将强制imap一次被评估
          【解决方案6】:

          这会从每个单词创建一个集合并将它们传递给 Counter 的构造函数。

          >>> from itertools import chain, imap
          >>> from operator import itemgetter
          >>> from collections import Counter
          >>> words = 'happy', 'harpy', 'hasty'
          >>> counter = Counter(chain.from_iterable(imap(set, words)))
          >>> map(itemgetter(0), counter.most_common())
          ['a', 'h', 'y', 'p', 's', 'r', 't']
          

          【讨论】:

            【解决方案7】:
            import collections
            
            cnt = collections.Counter('happy harpy hasty').keys()
            
            cnt = list(cnt)
            
            print(cnt)
            

            【讨论】:

            • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
            猜你喜欢
            • 2020-11-16
            • 1970-01-01
            • 2016-05-18
            • 1970-01-01
            • 2011-09-05
            • 2023-03-03
            • 1970-01-01
            • 2023-02-11
            • 1970-01-01
            相关资源
            最近更新 更多