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

Python – พิมพ์แถวที่ความถี่ทุกสมาชิกมากกว่า K

เมื่อต้องการพิมพ์แถว (สับลิสต์) ที่ความถี่ของทุกสมาชิกในแถวนั้นมากกว่า K สามารถใช้ฟังก์ชันช่วยที่มี all() และ count() ได้

ตัวอย่าง

def frequency_greater_K(row, K):
    return all(row.count(element) > K for element in row)

my_list = [[11, 11, 32, 43, 12, 23], [42, 14, 55, 62, 16], [11, 11, 11, 11], [42, 54, 61, 18]]
print("The tuple is :")
print(my_list)
K = 1
print("The value of K is :")
print(K)
my_result = [row for row in my_list if frequency_greater_K(row, K)]
print("The result is :")
print(my_result)

ผลลัพธ์

The tuple is : [[11, 11, 32, 43, 12, 23], [42, 14, 55, 62, 16], [11, 11, 11, 11], [42, 54, 61, 18]]
The value of K is : 1
The result is : [[11, 11, 11, 11]]

คำอธิบาย

  • กำหนดฟังก์ชัน frequency_greater_K ตรวจสอบว่า row.count(element) > K สำหรับทุก element ใน row

  • กำหนดเมทริกซ์และค่า K

  • ใช้ list comprehension กรองแถวที่ผ่านฟังก์ชันตรวจสอบ

  • แสดงผลลัพธ์เฉพาะแถวที่ทุกสมาชิกมีความถี่ > K