简体   繁体   English

如何使元音计数器和总和更简洁有效? 蟒蛇

[英]how to make vowel counter and sum more concise and efficient? Python

I am new to Stack Overflow, but noticed how helpful, and open this community is. 我是Stack Overflow的新手,但是注意到它很有帮助,因此打开了这个社区。 Just curious if there is anyway to make this vowel counter more concise/organized. 只是好奇是否有任何方法可以使此元音计数器更简洁/更有条理。 Any help would be appreciated, and an in-depth answer would be awesome as well. 任何帮助将不胜感激,并且深入的回答也将是很棒的。 Thank you! 谢谢!

def vowel_count(str):

    str = input("Please enter a sentence: ")
    str1 = (str.lower())
    #intialize count variable to zero
    count = 0

    #create a set of vowels
    vowel = set("aeiou")

    for alphabet in str1:
        if alphabet in vowel:
            count = count+1

    print("Number of vowels in this sentence is: " , count)
    print()
    print("A,E,I,O,U")
    print(*map(str.lower().count, "aeiou"))

vowel_count(str)    

I see that in your code example, you used a variable named str. 我在您的代码示例中看到,您使用了一个名为str的变量。 Don't do that, as str is a built-in function and this can lead to problems. 不要这样做,因为str是内置函数,这可能会导致问题。

What about this solution: 那这个解决方案呢:

string = input().lower()

print(sum([string.count(i) for i in "aeiou"]))

Firstly, I get the input, which I lower immediately. 首先,我得到输入,我立即降低了输入。 Then, I used the string.count(i) for every vowel, which in this case returns the amount of times i (one of the vowels) appears in the string (input). 然后,我为每个元音使用string.count(i),在这种情况下,它返回i(元音之一)出现在字符串(输入)中的次数。 I then called the sum function on the created array which returns the sum of all elements inside the array. 然后,我在创建的数组上调用sum函数,该函数返回数组中所有元素的总和。 Last but not least, I simply printed the value returned from this sum function. 最后但并非最不重要的一点是,我只打印了此求和函数返回的值。

If you don't understand how the argument passed to the sum function is an array, look into the topic of List Comprehension . 如果您不明白传递给sum函数的参数是一个数组,请查看List Comprehension主题。

I think you should use Counter . 我认为您应该使用Counter

from collections import Counter
In [1]: a = 'I am mayank'
In [5]: ans = Counter(a.lower())

In [6]: ans
Out[6]: Counter({' ': 2, 'a': 3, 'i': 1, 'k': 1, 'm': 2, 'n': 1, 'y': 1})

In [10]: ans['a']
Out[10]: 3

This will count the occurrence of each letter in the string including vowels. 这将计算字符串中每个字母(包括元音)的出现情况。 This should be quite efficient. 这应该非常有效。

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

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