字符串python 3中最常见的元音
我已经为字符串中最频繁的元音创建了程序,但我遇到的问题是,我只想为最频繁的元音打印一个字母,而不是两个字母。我的代码如下所示:字符串python 3中最常见的元音,python,string,if-statement,for-loop,Python,String,If Statement,For Loop,我已经为字符串中最频繁的元音创建了程序,但我遇到的问题是,我只想为最频繁的元音打印一个字母,而不是两个字母。我的代码如下所示: from collections import Counter words = input("Enter a line of text: ") vowel = "aeiouAEIOU" x = Counter(c for c in words.upper() if c in vowel) most = {k: x[k] for k in x if x[k] == ma
from collections import Counter
words = input("Enter a line of text: ")
vowel = "aeiouAEIOU"
x = Counter(c for c in words.upper() if c in vowel)
most = {k: x[k] for k in x if x[k] == max(x.values())}
for i in most:
vowel = i
y = most[i]
print("The most occuring vowel is:",vowel, "with",y,"occurences")
if vowel != words:
print("No vowels found in user input")
例如,当我运行代码时,我输入“aa ee”,它将打印:
The most occuring vowel is: A with 2 occurences
The most occuring vowel is: E with 2 occurrences
我只想让它打印A或E?为什么不简单地使用哪种最适合做这项工作
words = input("Enter a line of text: ")
vowels = set("aeiouAEIOU")
x = Counter(c for c in words if c in vowels)
print x.most_common()
还要注意的是,您不需要使用
word.upper
,因为您拥有所有的元音类型。正如在评论中所说的,您可以使用set
来保留元音,其成员检查复杂度为O(1)。“A或E”-好吧,哪一个?你让口译员创建一个字典,然后循环使用它。它怎么知道你想要哪一个?如果你只想要一个元音,为什么还要让它这么做呢?你想如何选择要显示的元音?或者这不重要吗?其他的调整:元音
应该是元音
,元音
应该是集合
,而集合
应该看起来像{a',E',I',O',U}
(因为你在做单词.upper()
它不需要包含小写)。我知道你只是在复制这个,但是…@AdamSmith是的,谢谢,但是我认为没有必要使用set
作为简而言之的iterables,但是它在单词中每个字符检查一次。一次查找转换为set
不同于N次查找转换为set
无需?是否有使用序列的“需要”?使用集合
会花费您一些钱吗?如果单词
非常大,并且要检查许多字符,该怎么办<代码>集合
始终是成员资格测试的正确选择。@AdamSmith Oh you man for单词
,但这将导致答案错误,因为OP想要找到元音的频率!