简体   繁体   English

Python:使用特定条件索引字符串

[英]Python: Indexing a string with specific conditions

I need help with this: Find the number of words that contain none of the five vowels and three y's. 我需要以下帮助: 查找不包含五个元音和三个y的单词数量。

So far, I have: 到目前为止,我有:

def no_vowels_yyy(s):
        count = 0
        list_of_vowels = ['a', 'e', 'i', 'o', 'u']
        for i in range(0, len(s)):
                if s[i] not in list_of_vowels and (s[i] == 'y') == 3:
                        return True
        return False

This is not working though... 虽然这不起作用...

Your check for the number of y's (s[i] == 'y') == 3: is what's causing it not to work. 您检查y的数量(s[i] == 'y') == 3:是导致它不起作用的原因。 Comparing s[i] to 'y' will give you a boolean (true/false) result, not the number of matches. s[i]'y'会得到布尔(真/假)结果,而不是匹配数。 Since you are looping through, you could just keep a count of the number of y's you've found. 由于您正在遍历,因此您只需保留找到的y数即可。

def no_vowels_yyy(s):
    count = 0
    list_of_vowels = ['a', 'e', 'i', 'o', 'u']
    for i in range(0, len(s)):
            if s[i] in list_of_vowels:
                return False
            if s[i] == 'y':
                count += 1

    return count == 3

Since others have already told you what's the problem, I'll just offer a solution of my own. 由于其他人已经告诉过您问题所在,因此我将提供自己的解决方案。 This is probably the best way, I can't see why not to use string.count() -method: 这可能是最好的方法,我不明白为什么不使用string.count() -方法:

def no_vowels_yyy(s):
    if any(c in {'a', 'e', 'i', 'o', 'u'} for c in s):
        return False
    return s.count('y') == 3

Here is a slightly different solution. 这是一个略有不同的解决方案。

First, we build a set of vowels. 首先,我们构建一set元音。 It is very fast to check if a particular character is in this set, or not; 检查特定字符是否在此集合中非常快捷; faster than checking in a list. 比检查列表更快。 Also, we build it once, outside the function, instead of building it every time the function is called. 另外,我们在函数外部只构建一次,而不是每次调用函数时都构建一次。

We use any() with a generator expression that checks each character to see if it is in the set. 我们将any()与生成器表达式一起使用,该表达式检查每个字符以查看其是否在集合中。 If any character is in the set of vowels, we return False. 如果元音组中有任何字符,则返回False。

Next, we use sum() with a generator expression to count how many 'y' characters there are; 接下来,我们使用带有生成器表达式的sum()来计算有多少个'y'字符; for each character that is a 'y' , the value 1 is added by the sum() function. 对于每个'y'字符,值1sum()函数sum() We return whether this result is 3. 我们返回此结果是否为3。

This will be a bit faster than looping over the string with an index and updating a counter variable. 这比遍历带有索引的字符串和更新计数器变量要快一些。 This is more of a "Pythonic" solution. 这更多是“ Pythonic”解决方案。 On the other hand, this loops over the string twice rather than once. 另一方面,这使字符串循环两次而不是一次。

_vowels = set(['a', 'e', 'i', 'o', 'u'])

def no_vowels_yyy(s):
    if any(ch in _vowels for ch in s):
        return False

    return s.count('y') == 3

print(no_vowels_yyy("zyzyxy"))

Just to show another way...: 只是为了显示另一种方式...:

from collections import Counter
def func(text):
    freq = Counter(text)
    return freq['y'] == 3 and not (freq.viewkeys() & 'aeiou')

Has the advantage of just one parse, but doesn't short circuit on vowels... 仅具有一次解析的优点,但不会使元音短路...

Otherwise, to short circuit as soon as possible: 否则,要尽快短路:

y_count = 0
for ch in word:
    if ch in {'a', 'e', 'i', 'o', 'u'}:
        return False
    elif ch == 'Y':
        y_count += 1
        if y_count > 3:
            return False
return y_count == 3
def no_vowels_yyy(s, _vowels=set("aeiou")):
    return s.count("y") == 3 and _vowels.isdisjoint(s)
print(no_vowels_yyy("zyzyxy")) # -> True

Or a more readable version: 或更可读的版本:

def no_vowels_yyy(s):
    return s.count("y") == 3 and all(c not in "aeiou" for c in s)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM