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

Python – ดึงแถวที่มีสตริงความยาวคู่


เมื่อต้องการดึงแถวที่มีสตริงความยาวเป็นเลขคู่ จะใช้ List Comprehension ร่วมกับตัวดำเนินการ all() และตัวดำเนินการ modulus (%)

ตัวอย่าง

my_list = [["python", "is", "best"], ["best", "good", "python"], ["is", "better"], ["for", "coders"]]
print("The list is :")
print(my_list)
my_result = [row for row in my_list if all(len(element) % 2 == 0 for element in row)]
print("The resultant list is :")
print(my_result)

ผลลัพธ์

The list is : [['python', 'is', 'best'], ['best', 'good', 'python'], ['is', 'better'], ['for', 'coders']]
The resultant list is : [['python', 'is', 'best'], ['best', 'good', 'python'], ['is', 'better']]

คำอธิบาย

  • กำหนดรายการของรายการสตริงและแสดงผลบนคอนโซล

  • ใช้ List Comprehension วนลูปผ่านสมาชิกของรายการ

  • ตรวจสอบว่าสตริงทุกตัวในแถวมีความยาวเป็นเลขคู่ด้วย all() และ %

  • หากผ่านเงื่อนไข จะเก็บแถวนั้นไว้ในรายการใหม่

  • แสดงผลลัพธ์บนคอนโซล