[英]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:我怎样才能删除:
['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
这是我使用
dropwhile
和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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.