这是字符串:
a='dqdwqfwqfggqwq'
如何获得每个角色的出现次数
我的老板告诉我,它只使用一行来做到这一点,
那我该怎么办
谢谢
效率不高,但它是一线的......
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}
在2.7和3.1中有一个名为Counter的工具:
>>> import collections
>>> results = collections.Counter("dqdwqfwqfggqwq")
>>> results
Counter({'q': 5, 'w': 3, 'g': 2, 'd': 2, 'f': 2})
Docs。正如评论中指出的那样,它与2.6或更低版本不兼容,但它是backported。
(备查)
这种各种方法的performance comparison可能会引起关注。
你可以这样做:
listOfCharac={}
for s in a:
if s in listOfCharac.keys():
listOfCharac[s]+=1
else:
listOfCharac[s]=1
print (listOfCharac)
输出{'d': 2, 'f': 2, 'g': 2, 'q': 5, 'w': 3}
这种方法也很有效,并且针对python3进行了测试。
对于每个字母计数字符串与该字母之间的差异,没有它,这样你就可以得到它的出现次数
a="fjfdsjmvcxklfmds3232dsfdsm"
dict(map(lambda letter:(letter,len(a)-len(a.replace(letter,''))),a))
lettercounts = {}
for letter in a:
lettercounts[letter] = lettercounts.get(letter,0)+1
一行代码,用于查找字符串中每个字符的出现次数。
for set in a(a):print('%s count is%d'%(i,a.count(i)))