簡體   English   中英

刪除多余的空字符串?

[英]Remove extra empty strings?

假設我有一個 Python 字符串列表,如下所示:

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

我怎樣才能刪除:

  1. 所有前導空字符串
  2. 所有尾隨空字符串
  3. 所有“重復”的空字符串
    (即將所有內部空值序列減少為單個值)

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

這是我使用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