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

ตรวจสอบว่า suffix ตรงกับสตริงในลิสต์หรือไม่ ใน Python


ปัญหา

ให้ลิสต์สตริง lst และสตริง suffix ตรวจสอบว่ามีสตริงในลิสต์ที่ลงท้ายด้วย suffix หรือไม่

วิธีที่ 1: ใช้ any() (แนะนำ)

lst = ["Tuesday", "Friday", "Sunday"]
suffix = "day"

if any(s.endswith(suffix) for s in lst):
    print(f"'{suffix}' is a suffix of some string in the list")
else:
    print(f"'{suffix}' is not a suffix")

วิธีที่ 2: ใช้ filter()

matches = list(filter(lambda s: s.endswith(suffix), lst))
if matches:
    print("Found:", matches)
else:
    print("Not found")

วิธีที่ 3: ใช้ List Comprehension

matches = [s for s in lst if s.endswith(suffix)]
print(bool(matches))

ตัวอย่างเพิ่มเติม: ตรวจสอบ prefix

prefix = "Sun"
any(s.startswith(prefix) for s in lst)

สรุป

any() สั้นที่สุดและหยุดทันทีเมื่อเจอ (short-circuit) เหมาะสำหรับเช็คเงื่อนไข