如何从Python列表的末尾删除“无”项

leeman:

有一个列表,其中可能包含无项目。我想删除这些项目,但前提是它们出现在列表的末尾,所以:

[None, "Hello", None, "World", None, None]
# Would become:
[None, "Hello", None, "World"]

我已经编写了一个函数,但是我不确定这是否是在python中进行处理的正确方法?:

def shrink(lst):
    # Start from the end of the list.
    i = len(lst) -1
    while i >= 0:
        if lst[i] is None:
            # Remove the item if it is None.
            lst.pop(i)
        else:
            # We want to preserve 'None' items in the middle of the list, so stop as soon as we hit something not None.
            break
        # Move through the list backwards.
        i -= 1

也可以使用列表理解作为替代方法,但是这似乎效率低下并且没有可读性吗?:

myList = [x for index, x in enumerate(myList) if x is not None or myList[index +1:] != [None] * (len(myList[index +1:]))]

从列表末尾删除“无”项目的pythonic方法是什么?

威姆:

从列表末尾丢弃很有效。

while lst[-1] is None:
    del lst[-1]

IndexError: pop from empty list如有必要,添加保护措施根据您的特定应用程序,将空白列表视为正常还是错误情况取决于您。

while lst and lst[-1] is None:
    del lst[-1]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章