เมื่อต้องการดึงคำที่ขึ้นต้นด้วยสระ (a, e, i, o, u) จากลิสต์ สามารถใช้ลูป iteration, ค่า flag และ startswith() ได้
ตัวอย่าง
my_list = ["abc", "phy", "and", "okay", "educate", "learn", "code"]
print("The list is :")
print(my_list)
my_result = []
my_vowel = "aeiou"
print("The vowels are ")
print(my_vowel)
for index in my_list:
my_flag = False
for element in my_vowel:
if index.startswith(element):
my_flag = True
break
if my_flag:
my_result.append(index)
print("The result is :")
print(my_result)
ผลลัพธ์
The list is : ['abc', 'phy', 'and', 'okay', 'educate', 'learn', 'code'] The vowels are aeiou The result is : ['abc', 'and', 'okay', 'educate']
คำอธิบาย
กำหนดลิสต์คำและสตริงสระ my_vowel
วนลูปแต่ละคำ ตั้ง flag=False วนลูปเช็คทุกสระ
ใช้
startswith()ตรวจสอบว่าคำขึ้นต้นด้วยสระนั้นหรือไม่ ถ้าใช่ flag=True breakถ้า flag=True เพิ่มคำนั้นในผลลัพธ์
แสดงผลลัพธ์คำที่ขึ้นต้นด้วยสระ