繁体   English   中英

如何从字符串列表的末尾删除空字符串(仅在末尾)

[英]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.

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