2
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)

我的代码不对,它会打印出原始列表中的所有单词。

4

6 回答 6

11
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']
于 2012-10-11T06:33:16.610 回答
7

这是一个带有列表理解的单行答案:

>>> print [w for w in words if w[0] in 'aeiou']
['apple', 'orange', 'otter', 'iguana', 'eagle']
于 2012-10-11T06:36:02.577 回答
7

好的 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]在于它不适用于空词(在此特定示例中无关紧要,但在解析用户输入等实际任务中很重要)。

于 2012-10-11T06:42:46.833 回答
2
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)
于 2012-10-11T06:34:17.243 回答
1

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)```
于 2021-03-10T11:26:07.623 回答
0

您可以使用列表理解:

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)
于 2022-02-22T13:34:09.253 回答