Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python đếm xuất hiện mỗi ký tự trong chuỗi

Bài toán: cho chuỗi, đếm số lần xuất hiện của mỗi ký tự.

Cách 1: Brute-force (dictionary đếm)

test_str = "Tutorialspoint"
count_dict = {}
for i in test_str:
    if i in count_dict:
        count_dict[i] += 1
    else:
        count_dict[i] = 1
print("Count of all characters in Tutorialspoint is :\n" + str(count_dict))
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}

Cách 2: Dùng collections.Counter

from collections import Counter
test_str = "Tutorialspoint"
res = Counter(test_str)
print("Count of all characters in Tutorialspoint is :\n" + str(dict(res)))
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}

Cách 3: Dùng set() trong dictionary comprehension

test_str = "Tutorialspoint"
res = {i: test_str.count(i) for i in set(test_str)}
print("Count of all characters in Tutorialspoint is :\n" + str(dict(res)))
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}

Kết luận

Đã học 3 cách đếm tần suất ký tự: dictionary thủ công, Counter, set comprehension.