我已经为字符串中最频繁的元音创建了程序,但我遇到的问题是我只打印一个字母用于最频繁的元音,而不是两者。我的代码显示如下:
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?
答案 0 :(得分:3)
为什么你不能简单地使用Counter.most_common()
这是最合适的工作方式?
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)。