如何在 Python 中从列表末尾删除'None'项



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

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

如果您不想修改列表,只需从右侧找到第一个不是 None 的索引并切到它:

def shrink(l):
for i in range(len(l) - 1, -1, -1):
if l[i] is not None:
return l[:i + 1]
return l[:0]

如果确实要就地修改列表,只需删除切片:

def shrink(l):
for i in range(len(l) - 1, -1, -1):
if l[i] is not None:
break
else:
i = -1
del l[i + 1:]

最简单的方法可能是你所做的。下面是一个概念上更简单的实现:

def shrink(lst):
copy_lst = lst[:]  # don't modify the original
while copy_lst[-1] is None:  # you can get the last element in 1 step with index -1
copy_list.pop()
return copy_lst

从python 3.8和walrus运算符开始,可以在列表理解中做到这一点,但这是一个黑客解决方案,你不应该使用它:

def shrink(lst):
at_end = True
return reversed([(at_end := e is None and at_end, e)[1] for e in reversed(lst) if not at_end])

最新更新