使用列表理解来获取 python 中具有多个 (3) 个元音的单词
Using list comprehension to get the words with multiple (3) vowels in python
这是我的问题
fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
# Use a list comprehension to make a variable named fruits_with_more_than_two_vowels. Hint: You'll need a way to check if something is a vowel.
我可以单独在列表推导中完成吗?
您可以使用正则表达式模式来过滤掉辅音。
import re
fruits = ["mango", "kiwi", "strawberry", "guava", "pineapple", "mandarin orange"]
results = [i for i in fruits if len(re.sub(r"[^aeiouAEIOU]", "", i)) > 2]
以上代码产生以下输出。
>>> results
["guava", "pineapple", "mandarin orange"]
def vowels_check(word):
vowels = 'aeiouAEIOU'
count = 0
for vowel in vowels:
count += word.count(vowel)
if count > 2: return True
return False
fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
fruits_with_more_than_two_vowels = [fruit for fruit in fruits if vowels_check(fruit)]
这是我的问题
fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
# Use a list comprehension to make a variable named fruits_with_more_than_two_vowels. Hint: You'll need a way to check if something is a vowel.
我可以单独在列表推导中完成吗?
您可以使用正则表达式模式来过滤掉辅音。
import re
fruits = ["mango", "kiwi", "strawberry", "guava", "pineapple", "mandarin orange"]
results = [i for i in fruits if len(re.sub(r"[^aeiouAEIOU]", "", i)) > 2]
以上代码产生以下输出。
>>> results
["guava", "pineapple", "mandarin orange"]
def vowels_check(word):
vowels = 'aeiouAEIOU'
count = 0
for vowel in vowels:
count += word.count(vowel)
if count > 2: return True
return False
fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
fruits_with_more_than_two_vowels = [fruit for fruit in fruits if vowels_check(fruit)]