Python- Count each letter in a list of words

后端 未结 7 1513
心在旅途
心在旅途 2021-01-16 05:46

So I have a list of words `wordList = list().\' Right now, I am counting each letter in each of the words throughout the whole list using this code

cnt = C         


        
相关标签:
7条回答
  • 2021-01-16 06:05

    An alternative approach using the iterator combinators in itertools:

    import collections
    import itertools
    
    cnt = collections.Counter(itertools.chain.from_iterable(itertools.imap(set, wordList)))
    
    0 讨论(0)
  • 2021-01-16 06:12
    cnt = Counter()
    for word in wordList:
        lSet = set(word)
        for letter in lSet:
            cnt[letter] +=1             
    
    0 讨论(0)
  • 2021-01-16 06:22
    cnt = Counter()
    for words in wordList:
          for letters in set(words):
              cnt[letters]+=1
    
    0 讨论(0)
  • 2021-01-16 06:24

    Add a set call:

    cnt = Counter()
    for word in wordList:
          for letter in set(word):
              cnt[letter]+=1
    
    0 讨论(0)
  • 2021-01-16 06:27

    You can eliminate a for with update, which updates count from an iterable (in this case, a string):

    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']
    
    0 讨论(0)
  • 2021-01-16 06:29
    import collections
    
    cnt = collections.Counter('happy harpy hasty').keys()
    
    cnt = list(cnt)
    
    print(cnt)
    
    0 讨论(0)
提交回复
热议问题