python关于字符串和列表计数
1. 新建哈希表(字典),循环遍历计数。
// 哈希表(字典)计数
def counter(s):
hash = {
}
# for index,item in enumerate(s):
for item in s:
if item in hash:
hash[item] = hash[item] + 1
else:
hash[item] = 1
return hash
if __name__ == '__main__':
s1 = [1,2,3,2,1,1,1,1,1,1]
s2 = 'abcaaaaabcc'
print(counter(s1))
print(counter(s2))
【输出】
{1: 7, 2: 2, 3: 1}
{‘a’: 6, ‘c’: 3, ‘b’: 2}
2. 库函数。
// 库函数计数
from collections import Counter
def counter_1(s1,s2):
return Counter(s1) + Counter(s2)
def counter_2(s1):
return s1.count(1)
if __name__ == '__main__':
s1 = [1,2,3,2,1,1,1,1,1,1]
s2 = 'abcaaaaabcc'
print(counter_1(s1, s2))
print(counter_2(s1))
Counter({1: 7, ‘a’: 6, ‘c’: 3, 2: 2, ‘b’: 2, 3: 1})
7