python count

http://www.runoob.com/python/att-list-count.html
http://www.runoob.com/python/att-string-count.html

count() 方法用于统计字符串里某个字符出现的次数。

可选参数为在字符串搜索的开始与结束位置。

str.count(sub, start= 0,end=len(string))

参数
sub – 搜索的子字符串
start – 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
end – 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
返回值
该方法返回子字符串在字符串中出现的次数。

str = "this is string example....wow!!!";
 
sub = "i";
print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
sub = "wow";
print "str.count(sub) : ", str.count(sub)
str.count(sub, 4, 40) :  2
str.count(sub) :  1

count() 方法用于统计某个元素在列表中出现的次数。

语法
count()方法语法:

list.count(obj)
参数
obj – 列表中统计的对象。

aList = [123, 'xyz', 'zara', 'abc', 123];

print "Count for 123 : ", aList.count(123);
print "Count for zara : ", aList.count('zara');
Count for 123 :  2
Count for zara :  1

统计字母频数

    astring = "abbcccdddd"
    d = {}
    for i in astring:
        if i not in d:        
            d[i] = astring.count(i)
    print (d)
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

你可能感兴趣的:(python)