python排序統計字符串

輸入字符串, 返回排序後的列表[(字符, 個數)]

count_num.py

str1 = "itesajlajlaf"
"""
方法二: 
    count = [0] * 1000 
    for x in str1:
        count[ord(x)] += 1 
    for i in range(0, len(count)):
        if count[i] > 0:
            print(chr(i) + str(count[i]), end="")
"""
dict1 = {}
for x in str1:
    if x not in dict1:
        dict1[x] = 1
    else:
        dict1[x] += 1

list1 = list(dict1.items())
list1.sort(key=lambda x: x[0])
print(list1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章