เมื่อต้องการกรอง tuple ที่ผลคูณมากกว่า K ใช้ list comprehension
ตัวอย่าง
สาธิตด้านล่าง:
def tuples_product(index):
my_result = 1
for element in index:
my_result *= element
return my_result
my_list = [(14, 25, 17), (2, 3, 5), (81, 42, 21), (6, 2, 1)]
print("The list is :")
print(my_list)
K = 15
print("The value of K is :")
print(K)
my_result = [index for index in my_list if tuples_product(index) > K]
print("The result is :")
print(my_result)
ผลลัพธ์
The list is : [(14, 25, 17), (2, 3, 5), (81, 42, 21), (6, 2, 1)] The value of K is : 15 The result is : [(14, 25, 17), (2, 3, 5), (81, 42, 21)]
คำอธิบาย
- กำหนดเมธอด 'tuples_product' รับ tuple คืนค่าผลคูณทุก element
- นอกเมธอด กำหนดลิสต์และแสดงผล
- กำหนดค่า K และแสดงผล
- ใช้ list comprehension วนลูป เรียกเมธอดเปรียบเทียบกับ K
- ถ้ามากกว่า K ใส่ในลิสต์กำหนดให้ตัวแปร
- แสดงผลลัพธ์บนคอนโซล