ในบทความนี้ เราจะเรียนรู้เกี่ยวกับวิธีแก้ปัญหาตามที่ระบุด้านล่าง
แจ้งปัญหา − เราได้รับสตริง เราจำเป็นต้องค้นหาการเกิดขึ้นของอักขระแต่ละตัวในสตริงที่กำหนด
เราจะพูดถึง 3 แนวทางดังที่กล่าวไว้ด้านล่าง:L
แนวทางที่ 1 − แนวทางเดรัจฉาน
ตัวอย่าง
test_str = "Tutorialspoint"
#count dictionary
count_dict = {}
for i in test_str:
#for existing characters in the dictionary
if i in count_dict:
count_dict[i] += 1
#for new characters to be added
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 - การใช้โมดูลคอลเลกชัน
ตัวอย่าง
from collections import Counter
test_str = "Tutorialspoint"
# using collections.Counter() we generate a 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() ในนิพจน์แลมบ์ดา
ตัวอย่าง
test_str = "Tutorialspoint"
# using set() to calculate unique characters in the given string
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} บทสรุป
ในบทความนี้ เราได้เรียนรู้เกี่ยวกับวิธีการค้นหาการเกิดขึ้นของอักขระแต่ละตัวในสตริงที่กำหนด