首页 > 解决方案 > 如何从 Python 列表的末尾删除“无”项

问题描述

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

[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方法是什么?

标签: pythonlist

解决方案


从列表末尾丢弃是有效的。

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

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

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

推荐阅读