【问题标题】:Join two for loops, separated by a print statement into one加入两个 for 循环,用 print 语句分隔成一个
【发布时间】: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 这是自动作业(?)它不适合真正的项目,所以简化问题根本没有意义。无论如何感谢您的建议!
  • 似乎辅音在字典中不合适 - 为什么不将其作为单独的变量保留?

标签: python for-loop


【解决方案1】:

另一种编写代码的方式可能是这样的:

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"

【讨论】:

  • @Greg 谢谢我正在检查! (并更改错字)>.
  • @Greg。如果您将第二个答案拆分为使用 2 个打印语句,也许会更好
  • @Greg 感谢您的回答,这有点超出我的想象,所以我正在弄清楚。收到后我会尽快查看,再次感谢!
  • @gnibbler:好点子,这使它更容易阅读并显示对称性。
  • @Greg:但是仍然有两个循环,这并没有达到问题的目的。
【解决方案2】:

你在优雅和其他更重要的事情上还有一些问题。首先,您的用户会反对必须键入您没有做任何有意义的事情的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

您可能希望将“发生”更改为“发生”。顺便说一句,如果元音的数量少于 2 个,输出就不是很漂亮。

【讨论】:

  • 你也可以使用ocurrances = dict.fromkeys('aeiou',0)
  • 非常感谢您的回答。在某些情况下,这是我们在课堂上做的一个非常简单的练习,我在尝试不同的事情时被挂断了,试图提高我对字典的熟悉程度,实际上我从外面的辅音开始,但把它们放在字典中以“复杂化”字典多一点,学习如何处理它。 0 是愚蠢练习的一部分,我同意这绝对很烦人。这永远不会实现,我只是对这种“相同”的循环很感兴趣,因为它们彼此如此接近,尽管我可以在第一个循环中适应所有内容。再次感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 2022-08-22
  • 1970-01-01
相关资源
最近更新 更多