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)
我的代码不对,它会打印出原始列表中的所有单词。
答案 0 :(得分:8)
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']
答案 1 :(得分:7)
以下是列表理解的单行答案:
>>> print [w for w in words if w[0] in 'aeiou']
['apple', 'orange', 'otter', 'iguana', 'eagle']
答案 2 :(得分:5)
好的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]
解决方案的问题在于它不适用于空单词(在此特定示例中无关紧要,但在解析用户输入等现实任务中很重要)。
答案 3 :(得分:1)
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)
答案 4 :(得分:0)
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)```