[英]How to remove empty strings from the end of a list of strings (only at the end)
我有一些字符串列表。 我想從列表的末尾刪除空字符串(即每個列表都應以非空元素結尾)。
input
list1= ['a1','b1','c1','d1','']
list2 = ['a2','','b2','','c2','d2','']
list3 = ['a3','','b3','','','']
list4 = ['','','','','']
輸出
list1= ['a1','b1','c1','d1']
list2 = ['a2','','b2','','c2','d2']
list3 = ['a3','','b3']
list4 = ['']
如果所有元素都是空字符串,則只應保留一個空字符串(例如 list4)。
您可以將生成器推導式與enumerate
使用,並從非空字符串的末尾開始保留第一個索引。 通過使用next
我們只需要迭代直到找到第一個非空字符串:
def trim_empty_end(l):
last_ix = next((ix for ix, i in enumerate(l[::-1]) if i), len(l)-1)
return l[:len(l) - last_ix]
trim_empty_end(['a1','b1','c1','d1',''])
# ['a1', 'b1', 'c1', 'd1']
trim_empty_end(['a2','','b2','','c2','d2',''])
# ['a2', '', 'b2', '', 'c2', 'd2']
trim_empty_end(['a3','','b3','','',''])
# ['a3', '', 'b3']
trim_empty_end(['','','','',''])
# ['']
這是使用str
方法的一種方法。
前任:
list1= ['a1','b1','c1','d1','']
list2 = ['a2','','b2','','c2','d2','']
list3 = ['a3','','b3','','','']
list4 = ['','','','','']
data = [list1, list2, list3, list4]
result = ["*#*".join(i).strip("*#* ").split("*#*") for i in data]
print(result)
輸出:
[['a1', 'b1', 'c1', 'd1'],
['a2', '', 'b2', '', 'c2', 'd2'],
['a3', '', 'b3'],
['']]
您可以使用遞歸
def remove_empty(l):
if l[-1] != "" or len(l) <= 1:
return l
return remove_empty(l[:-1])
print(remove_empty(list1)) # ['a1', 'b1', 'c1', 'd1']
print(remove_empty(list2)) # ['a2', '', 'b2', '', 'c2', 'd2']
print(remove_empty(list3)) # ['a3', '', 'b3']
print(remove_empty(list4)) # ['']
最簡單的方法(在我看來)
def remove_empty_at_end(l: list):
i = len(l) - 1
# If you're not sure the items of l are strings, then, you can do while l[i] == ""
while not l[i] and i > 0:
i -= 1
return l[:i + 1]
它很簡單,避免了創建無數的l
副本
def trim_empty_strings(l):
while len(l) > 1 and l[-1] == '':
l = l[:-1]
return l
trim_empty_strings(['a','b','', '']
trim_empty_strings(['','',''])
list1 = ['a1','b1','c1','d1','']
list2 = ['a2','','b2','','c2','d2','']
list3 = ['a3','','b3','','','']
list4 = ['','','','','']
data = [list1, list2, list3, list4] -->
data = [['a1','b1','c1','d1',''], ['a2','','b2','','c2','d2',''], ['a3','','b3','','',''], ['','','','','']]
for mysublist in data:
while (mysublist[-1].rstrip() == "" and len(mysublist) > 1):
del mysublist[-1]
對於數據中的每個子列表,如果 item 為空並且 item 不是唯一的* item,則刪除最后一個 item。
如果子列表末尾仍有空項目,請繼續執行此操作。
(*發問者:如果所有元素都是空字符串,則只應保留一個空字符串)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.