words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake', 'iguana',
'tiger', 'eagle']
vowel=[]
for vowel in words:
if vowel [0]=='a,e':
words.append(vowel)
print (words)
我的代码不对,它会打印出原始列表中的所有单词。
words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle']
for word in words:
if word[0] in 'aeiou':
print(word)
您也可以使用这样的列表理解
words_starting_with_vowel = [word for word in words if word[0] in 'aeiou']
这是一个带有列表理解的单行答案:
>>> print [w for w in words if w[0] in 'aeiou']
['apple', 'orange', 'otter', 'iguana', 'eagle']
好的 python 读起来几乎像自然语言:
vowel = 'a', 'e', 'i', 'o', 'u'
words = 'apple', 'orange', 'pear', 'milk', 'otter', 'snake', 'iguana', 'tiger', 'eagle'
print [w for w in words if w.startswith(vowel)]
解决方案的问题w[0]
在于它不适用于空词(在此特定示例中无关紧要,但在解析用户输入等实际任务中很重要)。
if vowel [0]=='a,e':
words.append(vowel)
您将其附加到此处的原始列表中。它应该是你的vowel
清单。
words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle']
vowel=[]
for word in words:
if word[0] in "aeiou":
vowel.append(word)
print (vowel)
使用列表理解
vowel = [word for word in words if word[0] in "aeiou"]
使用filter
vowel = filter(lambda x : x[0] in "aeiou",words)
res = []
list_vowel = "aeiou"
for sub in words:
flag = False
# checking for begin char
for ele in list_vowel:
if sub.startswith(ele):
flag = True
break
if flag:
res.append(sub)
# printing result
list_vowel = str(res)
print(list_vowel)```
您可以使用列表理解:
input_list = ['wood','oil','apple','bat','iron','Apple2']
list_vowel = [i for i in input_list if i[0] in "aeiouAEIOU"]
print(list_vowel)
或者可以使用
list1 = []
for i in input_list:
if i[0] in "aeiouAEIOU":
list1.append(i)
print(list1)