Let's say I have a Python list of strings like so:
x = ["", "", "test", "", "", "not empty", "", "yes", ""]
How can I remove:
['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.