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

Python – กรองแถวที่สมาชิกทุกตัวเป็นพหุคูณของ K


เมื่อต้องการกรองแถวที่สมาชิกทุกตัวเป็นพหุคูณของ K ใช้ list comprehension และตัวดำเนินการ modulus

ตัวอย่าง

สาธิตด้านล่าง:

my_list = [[15, 10, 25], [14, 28, 23], [120, 55], [55, 30, 203]] 
print("The list is :") 
print(my_list) 
K = 5 
print("The value of K is ") 
print(K) 
my_result = [index for index in my_list if all(element % K == 0 for element in index)] 
print("The result is :") 
print(my_result)

ผลลัพธ์

The list is : [[15, 10, 25], [14, 28, 23], [120, 55], [55, 30, 203]] 
The value of K is 5 
The result is : [[15, 10, 25], [120, 55]]

คำอธิบาย

  • กำหนดลิสต์ของลิสต์และแสดงผล
  • กำหนดค่า K และแสดงผล
  • ใช้ list comprehension วนลูปลิสต์ ตรวจสอบ modulus ของแต่ละ element กับ K เท่ากับ 0
  • ใช้ 'all' ตรวจสอบว่าทุก element ผ่านเงื่อนไข
  • ถ้า True เก็บไว้ในตัวแปร
  • แสดงผลลัพธ์บนคอนโซล