【发布时间】:2011-04-12 04:22:56
【问题描述】:
在下面的代码中,一切都按预期工作。
它得到一个以 0 结尾的 4 个字符长的用户输入。
并且只需在字典中添加元音和辅音的出现次数。
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"
只是感觉很草率。
我不喜欢它的是我调用了两次相同的 for 循环,我觉得这可能只是一个更优雅的方式,但我没有找到这样做的方法。
我想要实现的伪代码(或其他)如下。
loop the dictionary
print all key with values >= 1
print "were inserted" only once
print all the respective vales.
print "times respectively"
正如我所说,我想要相同的输出,但以更优雅的方式表达,我假设优雅意味着只有一个 for 循环,但欢迎使用任何其他(更优雅的)选项!
我想过做类似this 的事情,但显然行不通。 (别担心,这完全是错误的,但方法表明了我的目标)
提前致谢!
【问题讨论】:
-
我不知道python字符串连接的语法,但这将是使用单个循环并仍然生成指定输出的唯一方法。
-
@BenVoigt:哦,让我们看看,这听起来是个好主意!我会尝试一下。谢谢
-
组合循环。放弃“分别”并使输出更具可读性:a 被插入 1 次 e 被插入 1 次有 1 个辅音(或者这是一个家庭作业问题?)
-
@Steven 这是自动作业(?)它不适合真正的项目,所以简化问题根本没有意义。无论如何感谢您的建议!
-
似乎辅音在字典中不合适 - 为什么不将其作为单独的变量保留?