python - 如何从 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方法是什么?
解决方案
从列表末尾丢弃是有效的。
while lst[-1] is None:
del lst[-1]
IndexError: pop from empty list
如有必要,添加保护措施。这取决于您的特定应用程序是否应将处理空列表视为正常情况或错误情况。
while lst and lst[-1] is None:
del lst[-1]
推荐阅读
- python - 错误的发布请求正文会引发什么错误?
- python - Cannot import name SetDefaultColoring
- java - 使用 orderBy whereEqual 和 startAfter 查询 firestore
- python - Python Pandas: Filter rows based on position letter in string
- laravel - How to fix Paypal Checkout Order Creation Error
- vee-validate - Vee-validate 使用 3rd 方库扩展验证
- javascript - Ant design的“Step组件”这行怎么去掉?
- sql - 如何获取第二行
- excel - 我无法对单列数据集进行排序
- ssl - 科尔多瓦混合应用程序中的 NSURLErrorDomain 代码 1200 和 1004