繁体   English   中英

删除列表的元素,直到到达 Python 中的第一个空元素

[英]Remove element of list until getting to the first empty one in Python

我有这个字符串列表

list = ['1', '2', '3', '4', '', '    5', '    ', '    6', '', '']

我想在第一个空字符串之后获取每个项目以获得这个结果

list = ['    5', '    ', '    6', '', '']

请注意,我想留下后面的空字符串

我写了这个函数:

def get_message_text(list):
    for i, item in enumerate(list):
        del list[i]
        if item == '':
            break
    return list

但我无缘无故地得到了这个错误的结果:

['2', '4', '    5', '    ', '    6', '', '']

有什么帮助吗?

只需找到第一个空字符串的索引并对其进行切片:

def get_message_text(lst):
    try:
        return lst[lst.index("") + 1:]
    except ValueError:  # '' is not in list
        return [] # if there's no empty string then don't return anything

构造一个生成器,在尚未找到空字符串时丢弃该生成器。

如果需要列表,请使用list(get_message_text(lst))

否则在使用发电机for表达

for e in get_message_text(lst):

def get_message_text(lst):
    output = False
    for e in lst:
        if not output:
            if e == '': output = True
            continue
        yield e

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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