Python--find the most frequently occurring character in a string and the number of occurrences

method one:

1. Loop through the list or string, if the character is in the dictionary, add 1 to the value, if not, create (key, value) 2.
Find the largest value in the dictionary
3. Find the corresponding key according to the largest value value, print out the character with the most occurrences

    str = "abcabcabcaaab"
    dict = {}
    # 循环遍历列表或字符串,如果不在则创建(key,value),如果字符在字典中则值加1
    for i in str:
        if i not in dict:
            dict[i] = 1
        else:
            dict[i] += 1
    # 找到字典中,最大的value值
    temp = max(dict.values())
    # 根据最大的value值,找对应的key值,打印出出现次数最多的字符
    for k, v in dict.items():
        if v == temp:
            print("出现最多的是:", k, "出现了:", v)

Method Two:

1. With the feature that the dictionary key cannot be repeated, you can remove the repeated characters, and fill in the characters one by one in the dictionary. 2.
With the feature of the list for convenient value selection, add the elements in the dictionary to the list.
3. Bubble sorting, Put the character with the most occurrences first
4, return the first character, which is the character you want to find the most

    str = "abcabcabcaaab"
    d = {}
    # 用字典键不能重复的特点,就可以除去重复的字符,把字符转挨个填入字典中
    for i in str:
        count = str.count(i)
        d[i] = count
    #  用列表方便取值的特点,把字典中的元素添加到列表中
    list = []
    for i, v in d.items():
        list.append((i, v))
    # 冒泡排序,把出现次数最多的字符放到第一
    for i in range(len(list) - 1):
        for j in range(i + 1, len(list)):
            if list[i][1] < list[j][1]:
                list[i], list[j] = list[j], list[i]
    # 返回第一个字符,就是我们要找的次数最多的字符
    print("出现最多的是:", list[0][0], "出现了:", list[0][1])

Expansion: methods commonly used in dictionaries

1、get(key,default = None):

Returns the value of the specified key, or the value of default if the key does not exist

dic = {'a':1,'b':2,'c':3,'d':4}
print(dic.get('b'))
# 2
print(dic.get('e',5))
# 5

2、items( ):

Returns an iterable object of key-value pairs, which can be converted to [(key, value)] using list

dic = {'a':1,'b':2,'c':3,'d':4}
print(dic.items())
# dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
print(list(dic.items()))
# [('a', 1), ('b', 2), ('c', 3), ('d', 4)]

3、keys( ):

Returns an iterator that can be converted to a list using list()

dic = {'a':1,'b':2,'c':3,'d':4}
print(dic.keys())
# dict_keys(['a', 'b', 'c', 'd'])
print(list(dic.keys()))
# ['a', 'b', 'c', 'd']

4、values( ):

Returns an iterable object converted to a list of values ​​in the dictionary using list

dic = {'a':1,'b':2,'c':3,'d':4}
print(list(dic.values()))
# [1,2,3]

5. update (dictionary object):

update the dictionary object into the dictionary

dic = {'a':1,'b':2,'c':3,'d':4}
dic_two = {'f':6}
dic.update(dic_two)
print(dic)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'f': 6}

Guess you like

Origin blog.csdn.net/yuan_ahui/article/details/126036790