如何找出列表中以元音开头的单词?

2024-05-29 05:39:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

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


Tags: inappleforifeaglewordspeartiger
3条回答

下面是一个单行本的答案,包含列表理解:

>>> 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]解决方案的问题在于它不能处理空单词(在这个特定的示例中无关紧要,但在分析用户输入等实际任务中很重要)。

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']

相关问题 更多 >

    热门问题