将两个由打印语句分隔的for循环合并为一个
在下面的代码中,一切都按预期工作。
它获取一个长度为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个辅音
我想问的是关于这几行代码。
我知道一定有更好的方法来做:
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"
正如我所说,我想要相同的输出,但用更优雅的方式表达,我假设优雅的方式应该只用一个循环,但其他任何(更优雅的)选项也欢迎!
我考虑过做类似这个的事情,但显然不行。(别担心,这只是完全错误,但这个思路展示了我想要的方向)
提前谢谢你!
2 个回答
0
你还有一些问题需要解决,特别是关于优雅性和其他更重要的事情。首先,你的用户会反感必须输入一个0
,而你却没有对这个输入做任何有意义的处理。实际上,你还得专门写代码来忽略它!在字典里记录辅音的数量也显得不太优雅。你没有检查用户是否输入了所有字母,也没有处理大写字母。
下面是一段解决这些问题的代码,还有一些冗余的地方:
input = "" # get input from user
while len(input) != 3 or not input.isalpha():
input = raw_input("insert code:").lower()
ocurrances = {"a":0, "e":0, "i":0, "o":0, "u":0}
nconsonants = 0
for x in input:
if x in ocurrances:
ocurrances[x] += 1 #count vowels
else:
nconsonants += 1 #count consonants
for x in ocurrances:
if ocurrances[x]:
print x + ",",
print "were inserted",
for x in ocurrances:
if ocurrances[x]:
print str(ocurrances[x]) + ",",
print "times respectively"
if nconsonants == 1:
print "there was 1 consonant"
else:
print "there were %d consonants" % nconsonants
顺便提一下,你可能想把“ocurrances”改成“occurrences”。另外,如果元音的数量少于2,输出的结果就不太好看了。
2
另一种写代码的方法可能是这样的:
print ", ".join(k for k, v in occurrences.items() if k != "consonants" and v > 0),
print "were inserted"
print ", ".join(str(v) for k, v in occurrences.items() if k != "consonants" and v > 0),
print "times respectively"
你可以通过把搜索的部分提取出来,让这段代码更简洁一些:
a = [(k, str(v)) for k, v in occurrences.items() if k != "consonants" and v > 0]
print ", ".join(x[0] for x in a), "were inserted",
print ", ".join(x[1] for x in a), "times respectively"