text = input("enter string:")
text.lower()
counta = text.count ("a")
counte = text.count ("e")
counti = text.count ("i")
counto = text.count ("o")
countu = text.count ("u")
if counta > 0:
print ("'a'",counta)
if counte > 0:
print ("'e'",counte)
if counti> 0:
print ("'i'",counti)
if counto > 0:
print ("'o'",counto)
if countu > 0:
print ("'u':",countu)
leastFreq = [counta,counte,counti,counto,countu]
leastFreq.sort()
while 0 in leastFreq: leastFreq.remove(0)
print (leastFreq)
任务=计算单词中的元音,打印出现频率最低的元音。在本例中,“potato”将打印:
'a' = 1
'0' = 2
我怎样才能让它只印“a”?我可以使用min(leastFreq),但它只返回值“1”。我怎么做,使它打印使用格式'a'=1或如果有一个以上的元音出现相同的数目。你知道吗
要最小限度地更改代码:
但是你应该改用
collections.Counter
least_frequent
将是一个类似于('a', 1)
的元组编辑:如果您想要所有最常用的项目,可以使用
itertools.groupby
这看起来很复杂,但它所说的只是按排序顺序获取一个列表,并获取所有具有相同第二个值的元组,然后将它们放入一个列表中。你知道吗
计数器和运算符的组合可能会起到以下作用:
可以将^{} 与additional filter condition一起使用,测试元素是否为
> 0
:但是这样,你就失去了这个计数属于哪个字符的信息。您可以创建一个dictionary,将元音映射到它们各自的计数,而不是五个不同的变量:
然后再次将
min
与生成器表达式和特定的key
函数一起使用(按计数排序,而不是按元音本身排序)。你知道吗如果您对所有字母的计数感兴趣,也可以使用^{} 。你知道吗
相关问题 更多 >
编程相关推荐