從列表中提取以母音開頭的單詞的Python程式
當需要從列表中提取以母音開頭的單詞時,可以使用簡單的迭代、標誌值和“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']
解釋
定義一個列表並在控制檯上顯示。
建立一個空列表。
定義母音字串並在控制檯上顯示。
迭代列表,並將標誌賦值為布林值“False”。
如果每個字串的第一個元素以母音列表中的字元開頭,則布林標誌值設定為“True”。
這是使用“startswith”方法檢查的。
控制跳出迴圈。
如果布林標誌值為“True”,則將元素新增到空列表中。
這是在控制檯上顯示的輸出。
廣告