删除列表中的尾随空元素 [英] Removing trailing empty elements in a list

查看:58
本文介绍了删除列表中的尾随空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在一种优雅的python方式从列表中删除结尾的空元素? list.rstrip(None)的一种.所以

Is there an elegant pythonic way of removing trailing empty elements from a list? A sort of list.rstrip(None). So

[1, 2, 3, None, 4, None, None]

应该导致

[1, 2, 3, None, 4]

我想这可以概括为删除任何特定值的尾随元素.

I guess this could be generalized to removing trailing elements of any particular value.

如果可能,我希望将其作为单行(可读)表达式完成

If possible, I would like to have this done as a single line (readable) expression

推荐答案

如果只想删除None值并保留零或其他虚假值,则可以执行以下操作:

If you want to get rid of only None values and leave zeros or other falsy values, you could do:

while my_list and my_list[-1] is None:
    my_list.pop()

要删除所有伪造的值(零,空字符串,空列表等),您可以执行以下操作:

To remove all falsy values (zeros, empty strings, empty lists, etc.) you can do:

my_list = [1, 2, 3, None, 4, None, None]
while not my_list[-1]:
    my_list.pop()
print(my_list)
# [1, 2, 3, None, 4]

这篇关于删除列表中的尾随空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆