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:]))]
从列表末尾删除“无”项目的Python方法是什么?
答案 0 :(得分:45)
从列表末尾丢弃很有效。
while lst[-1] is None:
del lst[-1]
如有必要,为IndexError: pop from empty list
添加保护措施。视空列表还是正常情况而定,取决于您的特定应用。
while lst and lst[-1] is None:
del lst[-1]
答案 1 :(得分:3)
如果您不想修改列表,则可以从右边找到第一个索引(不是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:]
答案 2 :(得分:0)
最简单的方法可能就是您所做的。这是从概念上讲更简单的实现:
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运算符一样,可以进行列表理解,但这是一个hacky解决方案,您不应该使用它:
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])