将两个由 print 语句分隔的 for 循环连接成一个

发布于 2024-10-31 10:45:03 字数 1896 浏览 0 评论 0原文

在下面的代码中,一切都按预期工作。

它获取以 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的事情,但显然行不通。 (别担心,这完全是错误的,但该方法显示了我的目标)

提前致谢!

In the following code, everything is working as expected.

It gets a 4 character long user input that ends with 0.

And simply adds stores in a dictonary the occurances of vowels and consonants.

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"]

For the input "aef0" the program will print:

e, a, were inserted 1, 1, times
respectively there was 1 consonant

My questions is about this particular lines.

I know there must be a better way to do:

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"

It just feels sloppy.

What I don't like about it is that I'm calling twice the same for loop and I feel this could be only one move in a much more elegant way, but I'm not finding the way to do so.

A pseudo code (or whatever) of what I'm trying to achieve would be the following.

loop the dictionary
print all key with values >= 1
print "were inserted" only once
print all the respective vales.
print "times respectively"

As I said I want the same output, but expressed in a more elegant way, I'm assuming the elegant would imply only one for loop but any other (more elegant) options are welcome!

I thought about doing something like this, but it's obviously not working. (Don't worry about it, it's just plain wrong, but the approach shows what I was aiming for)

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

决绝 2024-11-07 10:45:03

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

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"

Another way to write your code might be something like this:

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"

You can shorten this a bit more by factoring out the search:

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"
我的黑色迷你裙 2024-11-07 10:45:03

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

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

You have a few more problems with elegance and other things that matter more. For a start your users would revolt against having to type a 0 that you don't do anything meaningful with. In fact you need to dedicate code to ignoring it! Keeping the count of consonants in the dict is rather inelegant. You don't check whether the user typed all letters. You don't handle uppercase.

Here's some code that addresses those issues plus a few verbosities:

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

and you might like to change "ocurrances" to "occurrences". By the way, if the number of vowels is less than 2, the output is not very pretty.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文