简体   繁体   中英

Remove extra empty strings?

Let's say I have a Python list of strings like so:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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