如何过滤以任何元音开头的字符串? [蟒蛇]

时间:2019-05-19 16:39:44

标签: python any

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

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)

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您可以使用集合来表示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

答案 2 :(得分:1)

您可以将tuple的允许开始输入到.startswith

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

输出:

this word starts with vowel
an
this word starts with vowel
anan
this word starts with vowel
ana
this word starts with vowel
a
this word starts with vowel
anana