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

โปรแกรม Python หา Tuple ที่สมาชิกทุกตัวหารด้วย K ลงตัวจาก List of Tuples

เมื่อต้องการกรอง tuple ที่สมาชิกทุกตัวหารด้วย K ลงตัว จาก list of tuples สามารถใช้ list comprehension ร่วมกับ all()

โค้ดตัวอย่าง

my_list = [(45, 90, 135), (71, 92, 26), (2, 67, 98)]
print("The list is:")
print(my_list)
K = 45
print("The value of K has been initialized to")
print(K)
my_result = [sub for sub in my_list if all(ele % K == 0 for ele in sub)]
print("Elements divisible by K are: " + str(my_result))

ผลลัพธ์

The list is: [(45, 90, 135), (71, 92, 26), (2, 67, 98)]
The value of K has been initialized to 45
Elements divisible by K are: [(45, 90, 135)]

คำอธิบาย

  • กำหนด list of tuples และค่า K

  • ใช้ list comprehension: [sub for sub in my_list if all(ele % K == 0 for ele in sub)]

  • all(ele % K == 0 for ele in sub) ตรวจสอบว่าทุก ele ใน sub หาร K ลงตัว

  • Tuple (45, 90, 135) ผ่านเงื่อนไข เพราะ 45÷45=1, 90÷45=2, 135÷45=3

ข้อควรระวัง: หาก K = 0 จะเกิด ZeroDivisionError ควรเพิ่มการตรวจสอบก่อนใช้งาน