【问题标题】:Loop Issue with Local Variable局部变量的循环问题
【发布时间】:2013-09-20 06:43:04
【问题描述】:

我正在使用 Python (3.x) 创建一个简单的作业程序。它需要一个多行输入,如果有多个连续的空格,它会删除它们并用一个空格替换它。 [这是最简单的部分。]它还必须打印整个输入中最连续空白的值。

例子:

input = ("This is   the input.")

应该打印:

This is the input.
3

我的代码如下:

def blanks():
    #this function works wonderfully!
    all_line_max= []
    while True:
        try:
            strline= input()
            if len(strline)>0:
                z= (maxspaces(strline))
                all_line_max.append(z)
                y= ' '.join(strline.split())
                print(y)
                print(z)
            if strline =='END':
                break
        except:
            break
        print(all_line_max)

def maxspaces(x):
    y= list(x)
    count = 0
    #this is the number of consecutive spaces we've found so far
    counts=[]
    for character in y:
        count_max= 0
        if character == ' ':
            count= count + 1
            if count > count_max:
                count_max = count
            counts.append(count_max)
        else:
            count = 0
    return(max(counts))


blanks()

我知道这可能非常低效,但它似乎几乎可以工作。我的问题是:一旦循环完成附加到 all_lines_max,我想打印该列表的最大值。但是,如果有意义的话,似乎没有一种方法可以打印该列表的最大值而不在每一行上都这样做。对我复杂的代码有什么想法吗?

【问题讨论】:

    标签: python loops python-3.x while-loop


    【解决方案1】:

    只需打印all_line_maxmax,就在您当前打印整个列表的位置:

    print(max(all_line_max))
    

    但将其留在 top 级别(如此 dedent 一次):

    def blanks():
        all_line_max = []
        while True:
            try:
                strline = input()
                if strline:
                    z = maxspaces(strline)
                    all_line_max.append(z)
                    y = ' '.join(strline.split())
                    print(y)
                if strline == 'END':
                    break
            except Exception:
                break
        print(max(all_line_max))
    

    并删除 print(z) 调用,该调用会打印每行的最大空白数。

    您的maxspaces() 函数将count_max 添加到您的counts 列表每次找到一个空间时;不是最有效的方法。你甚至不需要在那里保留一份清单; count_max 需要移出循环,然后才能正确反映最大空间计数。你也不必把句子变成一个列表,你可以直接遍历一个字符串:

    def maxspaces(x):
        max_count = count = 0
    
        for character in x:
            if character == ' ':
                count += 1
                if count > max_count:
                    max_count = count
            else:
                count = 0
    
        return max_count
    

    【讨论】:

    • 如果我使用建议的 print(max(all_line_max)),示例输入如下:1 3 5 3 1 4 我得到输出:1 3 5 3 5(其中的最大空格行)1 4 5(总体最大空间)如果可能的话,我希望只打印一张。
    • @Weens:是的,你需要 dedent 一次才能将其留在 while 循环之外。
    • 在这种情况下,如果在 while 循环之外,它似乎根本不会打印。那是让我一开始就绊倒的部分,这没有任何意义。
    • @Weens:对我有用;输入END,循环结束,并打印最大空间计数。
    • 啊哈!我的输入没有END。你可以说这里是凌晨 1 点 30 分。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    相关资源
    最近更新 更多