从列表中提取以元音开头的单词的Python程序
给定一个包含字符串元素的列表,以下程序提取以元音(a,e,i,o,u)开头的元素。
Input : test_list = [“all”, “love”, “get”, “educated”, “by”, “gfg”]
Output : [‘all’, ‘educated’]
Explanation : a, e are vowels, hence words extracted.
Input : test_list = [“all”, “love”, “get”, “educated”, “by”, “agfg”]
Output : [‘all’, ‘educated’, ‘agfg’]
Explanation : a, e, a are vowels, hence words extracted.
方法一:使用startswith()和loop
在这里,我们检查每个单词,并在每个单词的第一个字母表上使用 startswith() 检查它是否以元音开头。迭代部分使用循环完成。
Python3
# initializing list
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]
# printing original list
print("The original list is : " + str(test_list))
res = []
vow = "aeiou"
for sub in test_list:
flag = False
# checking for begin char
for ele in vow:
if sub.startswith(ele):
flag = True
break
if flag:
res.append(sub)
# printing result
print("The extracted words : " + str(res))
Python3
# initializing list
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]
# printing original list
print("The original list is : " + str(test_list))
res = []
vow = "aeiou"
for sub in test_list:
# check for vowel beginning
flag = any(sub.startswith(ele) for ele in vow)
if flag:
res.append(sub)
# printing result
print("The extracted words : " + str(res))
输出:
The original list is : [‘all’, ‘love’, ‘and’, ‘get’, ‘educated’, ‘by’, ‘gfg’]
The extracted words : [‘all’, ‘and’, ‘educated’]
方法 2:使用any() 、 startswith()和循环
在此,我们使用 any() 检查元音,其余功能与上述方法类似。
蟒蛇3
# initializing list
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]
# printing original list
print("The original list is : " + str(test_list))
res = []
vow = "aeiou"
for sub in test_list:
# check for vowel beginning
flag = any(sub.startswith(ele) for ele in vow)
if flag:
res.append(sub)
# printing result
print("The extracted words : " + str(res))
输出:
The original list is : [‘all’, ‘love’, ‘and’, ‘get’, ‘educated’, ‘by’, ‘gfg’]
The extracted words : [‘all’, ‘and’, ‘educated’]