簡體   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