Get the number of occurrences of each character

后端 未结 7 1532
说谎
说谎 2020-12-09 23:05

Given the string:

a=\'dqdwqfwqfggqwq\'

How do I get the number of occurrences of each character?

相关标签:
7条回答
  • 2020-12-09 23:38
    lettercounts = {}
    for letter in a:
        lettercounts[letter] = lettercounts.get(letter,0)+1
    
    0 讨论(0)
  • 2020-12-09 23:39

    Not highly efficient, but it is one-line...

    In [24]: a='dqdwqfwqfggqwq'
    
    In [25]: dict((letter,a.count(letter)) for letter in set(a))
    Out[25]: {'d': 2, 'f': 2, 'g': 2, 'q': 5, 'w': 3}
    
    0 讨论(0)
  • 2020-12-09 23:44

    You can do this:

    listOfCharac={}
    for s in a:
        if s in listOfCharac.keys():
            listOfCharac[s]+=1
        else:
            listOfCharac[s]=1
    print (listOfCharac)
    

    Output {'d': 2, 'f': 2, 'g': 2, 'q': 5, 'w': 3}

    This method is efficient as well and is tested for python3.

    0 讨论(0)
  • 2020-12-09 23:44

    (For future reference)

    This performance comparison of various approaches might be of interest.

    0 讨论(0)
  • 2020-12-09 23:45

    For each letter count the difference between string with that letter and without it, that way you can get it's number of occurences

    a="fjfdsjmvcxklfmds3232dsfdsm"
    dict(map(lambda letter:(letter,len(a)-len(a.replace(letter,''))),a))
    
    0 讨论(0)
  • 2020-12-09 23:45

    one line code for finding occurrence of each character in string.

    for i in set(a):print('%s count is %d'%(i,a.count(i)))

    0 讨论(0)
提交回复
热议问题