加入两个for循环,用print语句分隔成一个
在以下代码中,一切都按预期工作。
它获得一个4字符长的用户输入,以0结尾。
并且简单地将商店添加到元音和辅音的出现中。
input ="" #get input from user
while 4 < len(input) or 4 > len(input) or input[-1] != "0": #string has to be 4 char long and end in 0
input = raw_input("insert code:")
occurrences = {"a":0,"e":0,"i":0,"o":0,"u":0,"consonants":0} #store the vouel count
for x in input:
if x in occurrences.keys():
occurrences[x] += 1 #count cowels
elif x != "0":
occurrences["consonants"] += 1 #count consonants
for x in occurrences:
if occurrences[x] > 0 and x != "consonants":
print x + ",",
print "were inserted",
for x in occurrences:
if occurrences[x] > 0 and x != "consonants":
print str(occurrences[x]) + ",",
print "times respectively"
if occurrences["consonants"] == 1:
print "there was %d consonant"%occurrences["consonants"]
else:
print "there was %d consonants"%occurrences["consonants"]
对于输入“aef0”,程序将打印:
e,a,被插入1,1次
分别有1个辅音
我的问题是关于这一点。
我知道必须有更好的方法:
for x in ocurrances:
if ocurrances[x] > 0 and x != "consonants":
print x + ",",
print "were inserted",
for x in ocurrances:
if ocurrances[x] > 0 and x != "consonants":
print str(ocurrances[x]) + ",",
print "times respectively"
它只是感觉草率。
我不喜欢它的是我在循环中调用两次相同的东西,我觉得这可能只是一个更优雅的方式,但我找不到这样做的方法。
我正在尝试实现的伪代码(或其他)将如下所示。
loop the dictionary
print all key with values >= 1
print "were inserted" only once
print all the respective vales.
print "times respectively"
正如我所说,我想要相同的输出,但以更优雅的方式表达,我假设优雅意味着只有一个for循环,但欢迎任何其他(更优雅)的选项!
我想过做这样的事情,但显然不行。 (不要担心,这是完全错误的,但这种方法显示了我的目标)
提前致谢!
没有找到相关结果
已邀请:
2 个回复
旗低饶彤
您可以通过分解搜索来缩短这一点:
席陋临拈
你可能想把“ocurrances”改为“出现”。顺便说一下,如果元音的数量小于2,则输出不是很漂亮。