20210420-python-字符串中不同字符出现的次数

具体实践如下:

def find_str(str,find_str_list):
    # 定义列表保存每个字符出现的次数 弃用
    # count_list = []
    # 定义字典每次完成统计是字符和对应次数
    dict_str_count = {}
    for j in range(0,len(find_str_list)):
        '''
        方法一、
        使用count函数计算每一个字符的次数
        '''
        # str_count= str.count(find_str_list[j],0,len(str))
        # 初始化当前遍历的字符的次数=0  弃用
        # count_list.append(0)
        '''
        方法二、
        遍历查找目标范围,匹配时计数
        '''
        # 初始化次数
        str_count = 0
        for i in range(0,len(str)):

            if str[i] == find_str_list[j]:
                # print(i,str[i])
                str_count+=1
                # print(str_count)
        print(find_str_list[j],str_count)

        # # 得到当前遍历的字符+出现次数
        dict_str_count[find_str_list[j]] = str_count
    print(dict_str_count)
    '''
    方法一、
    dict_str_count.items()得到键值对列表,再调用sort函数进行排序,d:d[]指定通过键或值排序(0为键,1为值),默认正序排序,当reverse=True时,倒序
    '''
    dict_sort = sorted(dict_str_count.items(),key=lambda d: d[1],reverse=True)
    '''
    方法二、
    用key或value排序后,按照该排序,读取字典生成新的列表。
    但该方法只试用字典中key的排序,无法通过value得到key(除非value值唯一,但通常不唯一)。
    '''
    # dict_sort = {}
    # keys = dict_str_count.keys()
    # print('keys',keys)
    # keys_sort = sorted(keys)
    # print('key_sort',keys_sort)
    # for key in keys_sort:
    #     dict_sort[key] = dict_str_count[key]

    # 打印排序结果
    print(dict_sort)

    # 字典的key value反转
    # new_dict = {v: k for k, v in dict_str_count.items()}
    # print(new_dict)

#查找源

str = '你好我好大家好,我好他好好好好,你好吗?我很好!'

#输入3个字符

find_str1= '他'
find_str2= '我'
find_str3='你'
# 将输入字符放入一个列表,方便遍历
find_str_list = [find_str1,find_str2,find_str3]
find_str = find_str(str,find_str_list)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值