加入两个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循环,但欢迎任何其他(更优雅)的选项! 我想过做这样的事情,但显然不行。 (不要担心,这是完全错误的,但这种方法显示了我的目标) 提前致谢!     
已邀请:
编写代码的另一种方法可能是这样的:
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"
    
优雅和其他更重要的事情还有一些问题。首先,你的用户会反抗不必输入你没有做任何有意义的事情。实际上你需要专门的代码来忽略它!在字典中保持辅音的数量是相当不优雅的。您不检查用户是否键入了所有字母。你不处理大写。 这里有一些代码解决了这些问题以及一些冗长的问题:
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”改为“出现”。顺便说一下,如果元音的数量小于2,则输出不是很漂亮。     

要回复问题请先登录注册