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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12833512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:57:12  来源:igfitidea点击:

How to find out the words begin with vowels in a list?

pythonlistsearch

提问by user1718826

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)

My code doesn't right, and it will print out all the words in the original list.

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

采纳答案by John La Rooy

words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle']
for word in words:
    if word[0] in 'aeiou':
        print(word)

You can also use a list comprehension like this

您还可以使用这样的列表理解

words_starting_with_vowel = [word for word in words if word[0] in 'aeiou']

回答by st0le

if vowel [0]=='a,e':
        words.append(vowel)

You are appending it to the original list here. It should be your vowellist.

您将其附加到此处的原始列表中。它应该是你的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)

Using List comprehension

使用列表理解

vowel = [word for word in words if word[0] in "aeiou"]

Using filter

使用 filter

vowel = filter(lambda x : x[0] in "aeiou",words)

回答by K Z

Here is a one-liner answer with list comprehension:

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

>>> print [w for w in words if w[0] in 'aeiou']
['apple', 'orange', 'otter', 'iguana', 'eagle']

回答by georg

Good python reads almost like natural language:

好的 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)]

The problem with w[0]solution is that it doesn't work with empty words (doesn't matter in this particular example, but important in real-life tasks like parsing user input).

w[0]解决方案的问题在于它不适用于空词(在此特定示例中无关紧要,但在解析用户输入等现实任务中很重要)。