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

หาความถี่ในลิสต์ของทัพเปิลใน Python

คอนเทนเนอร์ข้อมูลหลายประเภทสามารถผสมกันใน Python ลิสต์สามารถมีองค์ประกอบแต่ละตัวเป็นทัพเปิล ในบทความนี้เราจะเอาลิสต์แบบนั้นมาและหาความถี่ขององค์ประกอบในทัพเปิลซึ่งเป็นองค์ประกอบของลิสต์

ใช้ count และ map

เราใช้ฟังก์ชัน lambda เพื่อนับผ่านแต่ละองค์ประกอบแรกในทัพเปิลที่อยู่ในลิสต์ จากนั้นใช้ฟังก์ชัน map เพื่อหาจำนวนรวมขององค์ประกอบที่เราค้นหา

ตัวอย่าง

# initializing list of tuples
listA = [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')]
# Given list
print("Given list of tuples : ", listA)
# Frequency in list of tuples
Freq_res = list(map(lambda i: i[0], listA)).count('Apple')
# printing result
print("The frequency of element is : ", Freq_res)

Output

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้:

Given list of tuples : [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')]
The frequency of element is : 2

ด้วย Counter

เราสามารถใช้ Counter ซึ่งจะนับจำนวนครั้งที่องค์ประกอบเกิดขึ้น เราใช้ลูป for เพื่อไปผ่านแต่ละทัพเปิลที่อยู่ในลิสต์

ตัวอย่าง

from collections import Counter
# initializing list of tuples
listA = [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')]
# Given list
print("Given list of tuples : ", listA)
# Frequency in list of tuples
Freq_res = Counter(i[0] for i in listA)['Apple']
# printing result
print("The frequency of element is : ", Freq_res)

Output

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ -

Given list of tuples : [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')]
The frequency of element is : 2