首页 > 解决方案 > 如何过滤以任何元音开头的字符串?[Python]

问题描述

字符串是“香蕉”。我已经创建了所有子字符串,现在想要过滤那些以元音开头或不以元音开头的子字符串。我想使用任何操作但不知道如何使用它。

l = ['', 'an', 'anan', 'na', 'ana', 'n', 'a', 'anana', 'ba', 'b', 'ban', 'nan', 'banan', 'banana', 'nana', 'bana']
vowels = 'aeiou'
for word in l:
    if word.startswith( any(vowels)): #this gives error
        print("this word starts with vowel")
        print(word)

标签: pythonany

解决方案


您可以使用集合来表示vowels而不是单个字符串,因此查找时间是O(1)而不是O(n),基本上它应该快一点:

words = ['', 'an', 'anan', 'na', 'ana', 'n', 'a', 'anana', 'ba', 'b', 'ban', 'nan', 'banan', 'banana', 'nana', 'bana']
vowels = {'a', 'e', 'i', 'o', 'u'}
for w in words:
  if len(w) > 0 and w[0] in vowels:
    print(f'"{w}" starts with a vowel')

输出:

"an" starts with a vowel
"anan" starts with a vowel
"ana" starts with a vowel
"a" starts with a vowel
"anana" starts with a vowel

推荐阅读