【问题标题】:Remove extra empty strings?删除多余的空字符串?
【发布时间】:2018-11-10 14:46:15
【问题描述】:

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

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

如何删除:

  1. 所有前导空字符串
  2. 所有尾随空字符串
  3. 所有“重复”的空字符串
    (即,将所有内部空白值序列减少为单个值)

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

【问题讨论】:

  • 您似乎希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的编码人员编写代码,但他们通常只有在发布者已经尝试自己解决问题时才会提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出以及您实际获得的输出(控制台输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask
  • 嗨,克里斯。您能否告诉我们您使用什么标准来确定要保留哪些空字符串以及要丢弃哪些空字符串?
  • @nat5142 当然,我想删除所有前导和尾随的空字符串(即,第一个字符串之前的所有字符串都有一些内容,最后一个字符串之后的所有字符串都有一些内容)。此外,对于内容字符串中间的所有空字符串,我想将倍数减少为单个空字符串(例如:[""、""] 到 [""])。
  • 这个问题不是太宽泛。问题陈述清晰,定义明确。问题是努力程度低,但解决方案是投反对票,而不是关闭。无论如何,@ChristopherCostello 考虑使用 groupby(x, key=bool) 来根据字符串是否为空来对字符串进行分组。

标签: python string list


【解决方案1】:
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]

【讨论】:

    【解决方案2】:

    这是我使用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']
    

    【讨论】:

      猜你喜欢
      • 2011-08-05
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-20
      相关资源
      最近更新 更多