day19

# 统计一句话中,有几个字母a 有几个单词glory
s = 'a bot, a gril, glory road is glory'
方法1 用list统计
lit_a = []
for i in s:
if i == 'a':
list_a.append(i)
len(list_a)
方法2,用变量统计
count= 0
for i in s:
if i == 'a':
count += 1
 
s1 = s.find('glory') # s1 = 15
s2 = s[int(s1+5):].find('glory') # s2 = 10
s[int(s1+5):][int(s2-1):]
 
s.count('glory')
 
# 删除一句话当中的所有a
# 思路,全部循环,判断如果是a 就跳过,然后在拼接起来
# s.replace('a', '') # 使用字符串替换函数
ss = ''
for i in s:
if i == 'a':
continue
s += i
 
# 统计一句话,每个字母出现的次数(提示:使用字典)
# 我的思路,有个误区,只用一个result统计,统计的是所有字母一共出现的次数
# 正常应该是先遍历,遍历之后就判断值是不是在新的字典当中,如果在,value就+1,如果不在,就是一个新出现的字母,对应的value初始化为1
count_dict = {}
for i in s:
count_dict[i] = 0
print(count_dict)
>>> result = 0
>>> for k in count_dict.items():
... if k != '':
... result += 1
# 老师的思路
for i in s:
if i in result:
result[i] += 1
else:
result[i] = 1
 

原文地址:https://www.cnblogs.com/jueshilaozhongyi/p/12089524.html