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

Python - กรอง Row ที่มีเฉพาะตัวอักษรจาก List of Lists

กรอง Sub-list (Row) ที่สมาชิกทุกตัวประกอบด้วยตัวอักษรเท่านั้น (Alphabetic) โดยใช้ str.isalpha()

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

my_list = [["python", "is", "best"], ["abc123", "good"], ["abc def ghij"], ["abc2", "gpqr"]]
print("The list is :")
print(my_list)

my_result = [sub for sub in my_list if all(element.isalpha() for element in sub)]

print("The result is :")
print(my_result)

ผลลัพธ์

The list is : [['python', 'is', 'best'], ['abc123', 'good'], ['abc def ghij'], ['abc2', 'gpqr']]
The result is : [['python', 'is', 'best']]

คำอธิบาย

  • element.isalpha() True ถ้าสตริงประกอบด้วยตัวอักษร A-Z, a-z เท่านั้น (ไม่มีช่องว่าง, ตัวเลข, สัญลักษณ์)
  • all(...) ต้อง True ทุก Element ใน Sub-list
  • Row 1: "python","is","best" -> ทุกตัว isalpha() = True
  • Row 2: "abc123" มีตัวเลข -> False
  • Row 3: "abc def ghij" มีช่องว่าง -> False
  • Row 4: "abc2" มีตัวเลข -> False