Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python หาจำนวนครั้งที่ตัวอักษรแต่ละตัวปรากฏในสตริง

ในบทความนี้ เราจะเรียนรู้วิธีแก้ปัญหาตามข้อกำหนดด้านล่าง

ข้อกำหนดปัญหา − เราได้รับสตริง ต้องหาจำนวนครั้งที่ตัวอักษรแต่ละตัวปรากฏในสตริงที่กำหนด

ที่นี่เราจะอภิปราย 3 วิธีตามด้านล่าง:

วิธีที่ 1 − Brute-force approach

ตัวอย่าง

test_str = "Tutorialspoint"
# count dictionary
count_dict = {}
for i in test_str:
    # สำหรับตัวอักษรที่มีอยู่ใน dictionary แล้ว
    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}

วิธีที่ 2 − ใช้โมดูล collections

ตัวอย่าง

from collections import Counter
test_str = "Tutorialspoint"
# ใช้ collections.Counter() สร้าง dictionary
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}

วิธีที่ 3 − ใช้ set() ใน lambda expression

ตัวอย่าง

test_str = "Tutorialspoint"
# ใช้ set() คำนวณ unique characters ในสตริงที่กำหนด
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}

สรุป

ในบทความนี้ เราได้เรียนรู้ 3 วิธีนับจำนวนตัวอักษรในสตริง: manual dict, collections.Counter, และ dict comprehension กับ set() ทุกวิธีให้ผลลัพธ์เดียวกัน