简体   繁体   English

删除多余的空字符串?

[英]Remove extra empty strings?

Let's say I have a Python list of strings like so:假设我有一个 Python 字符串列表,如下所示:

x = ["", "", "test", "", "", "not empty", "", "yes", ""]

How can I remove:我怎样才能删除:

  1. all leading empty strings所有前导空字符串
  2. all trailing empty strings所有尾随空字符串
  3. all 'repeated' empty strings所有“重复”的空字符串
    (ie reduce all internal sequences of empty space values to a single value) (即将所有内部空值序列减少为单个值)

['test', '', 'not empty', '', 'yes']

content = list(x.next() for i, x in it.groupby(content))
b_l_rgx = r"^(\s+)?$"
if re.match(b_l_rgx, content[0]):
    del content[0]
if len(content) > 0 and re.match(b_l_rgx, content[-1]):
    del content[-1]

Here's the solution I came up with using dropwhile and groupby这是我使用dropwhilegroupby提出的解决方案

from itertools import groupby, dropwhile

def spaces(iterable):
    it = dropwhile(lambda x: not x, iterable)
    grby = groupby(it, key=bool)
    try:
        k, g = next(grby)
    except StopIteration:
        return
    yield from g
    for k, g in grby:
        if k:
            yield ''
            yield from g

x = ["", "", "test", "", "", "not empty", "", "yes", ""]
print(list(spaces(x)))
# ['test', '', 'not empty', '', 'yes']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM