1

所以我需要我的程序的输出看起来像:

ababa
ab ba 
 xxxxxxxxxxxxxxxxxxx
that is it followed by a lot of spaces .
 no dot at the end
The largest run of consecutive whitespace characters was 47.

但我得到的是:

ababa

ab ba

xxxxxxxxxxxxxxxxxxx
that is it followed by a lot of spaces .
no dot at the end
The longest run of consecutive whitespace characters was 47.

当进一步查看我编写的代码时,我发现print(c)发生这种情况的语句:

['ababa', '', 'ab           ba ', '', '                                      xxxxxxxxxxxxxxxxxxx', 'that is it followed by a lot of spaces                         .', '                                               no dot at the end']

在某些行之间,有, '',,这可能是我的打印语句不起作用的原因。

我将如何删除它们?我尝试过使用不同的列表函数,但我不断收到语法错误。

这是我制作的代码:

  a = '''ababa

    ab           ba 

                                      xxxxxxxxxxxxxxxxxxx
that is it followed by a lot of spaces                         .
                                               no dot at the end'''


c = a.splitlines()
print(c)

#d = c.remove(" ") #this part doesnt work
#print(d)

for row in c:
    print(' '.join(row.split()))

last_char = ""
current_seq_len = 0
max_seq_len = 0

for d in a:
    if d == last_char:
        current_seq_len += 1
        if current_seq_len > max_seq_len:
            max_seq_len = current_seq_len
    else:
        current_seq_len = 1
        last_char = d
    #this part just needs to count the whitespace

print("The longest run of consecutive whitespace characters was",str(max_seq_len)+".")
4

3 回答 3

2

据我所知,您最简单的解决方案是使用列表理解

c= [item for item in a.splitlines() if item != '']

如果您希望通过删除仅包含空格的字符串(例如 )来使其更加健壮' ',则可以按如下方式更改它:

c= [item for item in a.splitlines() if item.strip() != '']

然后,您还可以将其重新加入列表,如下所示:

output = '\n'.join(c)
于 2013-09-20T11:48:32.317 回答
2

正则表达式时间:

import re

print(re.sub(r"([\n ])\1*", r"\1", a))
#>>> ababa
#>>>  ab ba 
#>>>  xxxxxxxxxxxxxxxxxxx
#>>> that is it followed by a lot of spaces .
#>>>  no dot at the end

re.sub(matcher, replacement, target_string)

Matcher 的r"([\n ])\1*意思是:

([\n ]) → match either "\n" or " " and put it in a group (#1)
\1*     → match whatever group #1 matched, 0 or more times

而替换只是

\1 → group #1

你可以得到最长的空白序列

max(len(match.group()) for match in re.finditer(r"([\n ])\1*", a))

它使用相同的匹配器,但只是获取它们的长度,然后maxs 它。

于 2013-09-20T11:51:48.253 回答
1

这可以通过内置filter函数轻松解决:

c = filter(None, a.splitlines())
# or, more explicit
c = filter(lambda x: x != "", a.splitlines())

第一个变体将创建一个列表,其中包含返回的列表a.splitlines()中不计算为的所有元素False,例如空字符串。第二个变体创建一个小的匿名函数(使用lambda)检查给定元素是否为空字符串,False如果是则返回。这比第一个变体更明确。

另一种选择是使用实现相同目的的列表推导:

c = [string for string in a.splitlines if string]
# or, more explicit
c = [string for string in a.splitlines if string != ""]
于 2013-09-20T11:45:07.913 回答