เมื่อต้องการค้นหาคำที่ใช้บ่อยที่สุดในรายการสตริง รายการจะถูกวนซ้ำและใช้วิธี "สูงสุด" เพื่อนับจำนวนสตริงสูงสุด
ตัวอย่าง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน
from collections import defaultdict
my_list = ["python is best for coders", "python is fun", "python is easy to learn"]
print("The list is :")
print(my_list)
my_temp = defaultdict(int)
for sub in my_list:
for word in sub.split():
my_temp[word] += 1
result = max(my_temp, key=my_temp.get)
print("The word that has the maximum frequency :")
print(result) ผลลัพธ์
The list is : ['python is best for coders', 'python is fun', 'python is easy to learn'] The word that has the maximum frequency : python
คำอธิบาย
-
แพ็คเกจที่จำเป็นจะถูกนำเข้าสู่สภาพแวดล้อม
-
รายการสตริงถูกกำหนดและแสดงบนคอนโซล
-
พจนานุกรมของจำนวนเต็มถูกสร้างขึ้นและกำหนดให้กับตัวแปร
-
รายการสตริงจะถูกทำซ้ำและแยกตามช่องว่าง
-
นับทุกคำจะถูกกำหนด
-
ค่าสูงสุดของค่าเหล่านี้กำหนดโดยใช้วิธี "สูงสุด"
-
สิ่งนี้ถูกกำหนดให้กับตัวแปร
-
สิ่งนี้จะแสดงเป็นเอาต์พุตบนคอนโซล