Python編程題18--統計字母出現次數並排序

題目

給定一個列表,列表元素僅包含字母,請統計每個字母的出現次數,並按出現次數排序,要求最終返回結果爲字典形式。

例如:

給定一個列表:['a', 'a', 'c', 'b', 'd', 'c', 'c', 'c', 'd', 'd']
返回結果:{"c": 4, "d": 3, "a": 2, "b": 1}

實現思路1

  • 利用 Python 裏的計數器 Counter ,其可用於追蹤值的出現次數,並返回一個 Counter 類對象,是字典 dict 的子類
  • 利用 Python 裏的內置函數 sorted() 並結合匿名函數 lambda 進行排序,設置 reverse=True 表示降序
  • 把結果轉換爲字典 dict 形式返回

注意:sorted() 返回的結果是一個新的列表list ,這裏需要轉換爲字典格式再返回

代碼實現

from collections import Counter

def demo(str_list):
    temp = Counter(str_list)
    res_list = sorted(temp.items(), key=lambda x: x[1], reverse=True)
    res_dict = dict(res_list)
    return res_dict

str_list = ["a", "a", "c", "b", "d", "c", "c", "c", "d", "d"]
print(demo(str_list))

實現思路2

  • 設置1個空字典 temp_dict ,用於存儲列表中的字母及其出現次數
  • 遍歷列表,如果當前字母不在字典中,那麼就將該字母作爲鍵存儲到字典,其鍵值爲 1 ;如果當前字母在字典中,那麼就讓字典中對應的鍵值加 1
  • 通過字典的 keys()values() 方法得到字母列表 key_list 及對應的字母次數列表 value_list
  • 對字母次數列表 value_list 進行排序,這裏用的冒泡排序,在從小到大排序的時候,同時對字母列表 key_list 也進行排序,以保證字母和出現次數相對應
  • 排序後,通過內置函數 zip() ,把2個列表轉爲字典,並按字母出現次數排序

代碼實現

def demo(str_list):
    temp_dict = {}
    for i in str_list:
        if i not in temp_dict:
            temp_dict[i] = 1
        else:
            temp_dict[i] += 1
    key_list = list(temp_dict.keys())
    value_list = list(temp_dict.values())
    for i in range(len(value_list) - 1):
        for j in range(len(value_list) - i - 1):
            if value_list[j] > value_list[j + 1]:
                value_list[j], value_list[j + 1] = value_list[j + 1], value_list[j]
                key_list[j], key_list[j + 1] = key_list[j + 1], key_list[j]
    res_dict = dict(zip(key_list[::-1], value_list[::-1]))
    return res_dict

str_list = ["a", "a", "c", "b", "d", "c", "c", "c", "d", "d"]
print(demo(str_list))

實現思路3

  • 設置1個空列表 temp_list ,用於存放字母及其出現次數,其元素通過 元組的方式 (字母, 次數) 來添加
  • 設置一個集合 temp_set ,用於存放列表中的所有字母
  • 對集合進行遍歷,遍歷的同時把字母及其出現次數添加到 temp_list
  • 對 temp_list 中的元素,按字母出現次數從小到大進行排序
  • 通過內置函數 dict() ,將列表轉換爲字典,並按字母出現次數排序

代碼實現

def demo(str_list):
    temp_list = []
    temp_set = set(str_list)
    for i in temp_set:
        temp_list.append((i, str_list.count(i)))
    for i in range(len(temp_list) - 1):
        for j in range(len(temp_list) - i - 1):
            if temp_list[j][1] > temp_list[j + 1][1]:
                temp_list[j], temp_list[j + 1] = temp_list[j + 1], temp_list[j]
    res_dict = dict(temp_list[::-1])
    return res_dict

str_list = ["a", "a", "c", "b", "d", "c", "c", "c", "d", "d"]
print(demo(str_list))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章