检查字符串中元音的存在 [英] Check presence of vowels in a string

查看:27
本文介绍了检查字符串中元音的存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查单词中是否存在元音.如果是,则应对单词say op(word) 进行操作.我想避免 for 循环,因为我想到了这一点:

I need to check whether a vowel is present in a word. If it is, an operation should be carried out on the word say op(word). I want to avoid a for loop because I thought of this:

for char in word:
    if char in 'aeiou':
#confused here... 

请推荐一种在执行时间方面成本较低的方法.另外,也帮我改正上面的方法.

Please, recommend a method that is low in cost when it comes to execution time. Also, help me correct the above approach too.

推荐答案

vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
if any(char in vowels for char in word):
   ...

注意:这更好,因为一旦它在单词中找到元音,它就会短路.因此,除非字符串中没有元音,否则它不必检查所有字符.

Note: This is better because it short circuits, as soon as it finds the vowel in the word. So, it doesn't have to check all the characters unless there are no vowels in the string.

运行timeit 测试和发现,@falsetru's answer 非常快,但几乎没有优化,re 版本胜过其他一切.

Ran a timeit test and found that, @falsetru's answer is extremely fast, but with few optimizations, the re version beats everything else.

import re

vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
pattern = re.compile("[AEIOUaeiou]")

def intersection():
    return bool(vowels.intersection("TWYNDYLLYNGS"))

def any_version():
    return any(char in vowels for char in "TWYNDYLLYNGS")

def re_version():
    return bool(pattern.search("TWYNDYLLYNGS"))

def disjoint():
    return vowels.isdisjoint("TWYNDYLLYNGS")

from timeit import timeit

print timeit("intersection()", "from __main__ import intersection, vowels")
print timeit("any_version()", "from __main__ import any_version, vowels")
print timeit("re_version()", "from __main__ import re_version, vowels")
print timeit("disjoint()", "from __main__ import disjoint, vowels")

这篇关于检查字符串中元音的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆