例如:Python:我如何找到一个字符串中的每个字符的列表?
>>> str = "aaabbc"
我怎么会得到一个输出这样的:提前
str.count(a) = 3
str.count(b) = 2
str.count(c) = 1
str.count(d) = 0
感谢。
例如:Python:我如何找到一个字符串中的每个字符的列表?
>>> str = "aaabbc"
我怎么会得到一个输出这样的:提前
str.count(a) = 3
str.count(b) = 2
str.count(c) = 1
str.count(d) = 0
感谢。
In [27]: mystr = "aaabbc"
In [28]: collections.Counter(mystr)
Out[28]: Counter({'a': 3, 'b': 2, 'c': 1})
In [29]: dict(collections.Counter(mystr))
Out[29]: {'a': 3, 'b': 2, 'c': 1}
值得注意的计数器进来2.7 + –
from collections import defaultdict
d = defaultdict(int)
for ltr in my_string:
d[ltr] += 1
print d
这个已经被问了几次才......
这里是在Python 2.7 <
只要OP没有被一个古老的python2.4卡住:-p – mgilson
好点先生:) –
工程,并使用正则表达式的答案,你是不是仅限于一个单一的字符,但:
import re
p = re.compile("a")
len(p.findall("aaaaabc")) //5
如果你想了解更多,请访问这里:http://docs.python.org/2/howto/regex.html。
这几乎肯定不是“正确”的方式来做到这一点(即使它的工作原理) –
如果他需要计数多于一个字符,或者更好的复杂模式,它其实是非常正确的。 OP没有真正描述他需要这样做,所以我只是让他知道一个可扩展的做事方式。 – corazza
考虑您还想0返回不在字符串中的元素,你可以试试这个:
def AnotherCounter (my_string, *args):
my_dict = {ele : 0 for ele in args}
for s in my_string:
my_dict[s] +=1
return my_dict
结果:
>>> AnotherCounter("aaabbc", 'a', 'b', 'c', 'd')
{'a': 3, 'c': 1, 'b': 2, 'd': 0}
您的代码实际上是有效的(如果效率不高)。 –