如何从列表末尾删除 None 的所有实例?
Python 有一个名为 rstrip() 的字符串方法:
>>> s = "hello world!!!"
>>> s.rstrip("!")
'hello world'
我想为 Python 列表实现类似的功能。也就是说,我想从列表末尾删除给定值的所有实例。在本例中,该值为None
。
这是一些开始的例子:
[1, 2, 3, None]
[1, 2, 3, None, None, None]
[1, 2, 3, None, 4, 5]
[1, 2, 3, None, None, 4, 5, None, None]
我希望最终结果是:
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, None, 4, 5]
[1, 2, 3, None, None, 4, 5]
这是到目前为止我的解决方案:
while l[-1] is None:
l.pop()
Python has a string method called rstrip()
:
>>> s = "hello world!!!"
>>> s.rstrip("!")
'hello world'
I want to implement similar functionality for a Python list. That is, I want to remove all instances of a given value from the end of a list. In this case, the value is None
.
Here's some starting examples:
[1, 2, 3, None]
[1, 2, 3, None, None, None]
[1, 2, 3, None, 4, 5]
[1, 2, 3, None, None, 4, 5, None, None]
I want the end results to be:
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, None, 4, 5]
[1, 2, 3, None, None, 4, 5]
Here's my solution so far:
while l[-1] is None:
l.pop()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想就地修改列表,那么您的解决方案很好,只需确保处理列表为空时的情况:
如果您想计算一个新列表,您可以将您的解决方案调整为:
还有 < a href="https://docs.python.org/3/library/itertools.html#itertools.dropwhile" rel="nofollow noreferrer">
itertools.dropwhile
,但是你必须执行两个逆转:If you want to modify the list in-place, then your solution is good, just make sure you handle the case when the list is empty:
If you want to compute a new list, you can adapt your solution into:
There is also
itertools.dropwhile
, but you have to perform two reversals:另外两个版本也适用于仅
None
的列表:对
l = [None] * 10**3
上的一些解决方案进行基准测试:请注意
stripNone2
和stripNone6
有一个小缺陷:如果 TraillineNone
中有一个对象不是None
但声称等于None
,那么它将被删除。不过,这样的物体非常不寻常。也许人们实际上也想要删除这样一个对象。基准代码:
Two more versions that also work for
None
-only lists:Benchmarking some solutions on
l = [None] * 10**3
:Note that
stripNone2
andstripNone6
have a small flaw: If there's an object among the trailineNone
s that isn'tNone
but claims to equalNone
, then it'll get removed. Such an object would be highly unusual, though. And perhaps one would actually want to remove such an object as well.Benchmark code: