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

กรองแถวที่ไม่มีช่องว่าง (Space) ในสตริงด้วย Regex

แนวคิด

จากลิสต์ของลิสต์สตริง ให้คืนเฉพาะแถวที่ "ทุกสตริงในแถว" ไม่มีช่องว่าง (whitespace) ใช้ regex \s ตรวจจับ whitespace

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

import re

my_list = [["python is", "fun"], ["python", "good"], ["python is cool"], ["love", "python"]]
print("ลิสต์:", my_list)

# list comprehension + regex
my_result = [
    row for row in my_list 
    if not any(bool(re.search(r"\s", element)) for element in row)
]

print("แถวที่ไม่มีช่องว่างเลย:", my_result)

ผลลัพธ์

ลิสต์: [['python is', 'fun'], ['python', 'good'], ['python is cool'], ['love', 'python']]
แถวที่ไม่มีช่องว่างเลย: [['python', 'good'], ['love', 'python']]

คำอธิบาย

  • re.search(r"\s", element) ค้นหา whitespace ใดๆ (space, tab, newline)
  • bool(...) แปลง match object เป็น True/False
  • any(...) True ถ้ามีอย่างน้อย 1 สตริงในแถวมี whitespace
  • not any(...) True ก็ต่อเมื่อ "ไม่มีสตริงไหนมี whitespace"

วิธีอื่นไม่ใช้ Regex

# ใช้ str.isspace() หรือ ' ' in string
my_result = [
    row for row in my_list 
    if not any(' ' in element for element in row)
]
# หรือ
my_result = [
    row for row in my_list 
    if all(not any(c.isspace() for c in element) for element in row)
]