有没有办法在列表对象上使用strip()? - 蟒蛇

DeF*_*FOX -1 python

现在我有一个像这样的列表对象:

lst = [None, None, 'one', None, 'two', None]
Run Code Online (Sandbox Code Playgroud)

我正在尝试对它执行strip()并获得如下结果:

strip(lst)

>> ['one', None, 'two']

left_strip(lst)

>> ['one', None, 'two', None]
Run Code Online (Sandbox Code Playgroud)

这样做有一种优雅的方式吗?

PS:感谢4 @ woockashek的建议,我已经改变了地表温度
[None, None, 'one','two', None][None, None, 'one', None, 'two', None]

Seb*_*zny 6

要获得类似的行为,left_strip您需要dropwhileitertools以下位置导入:

>>> lst=[None, None, 'one', None, 'two', None, None]
>>> from itertools import dropwhile
>>> def left_strip(lst):
        return list(dropwhile(lambda x : x is None, lst))
>>> left_strip(lst)
['one',None, 'two', None, None]
Run Code Online (Sandbox Code Playgroud)

获得如下行为right_strip:

>>> from itertools import dropwhile
>>> def right_strip(lst):
        return list(reversed(left_strip(reversed(lst))))
>>> right_strip(lst)
[None, None, 'one', None, 'two']
Run Code Online (Sandbox Code Playgroud)

要按strip顺序运行:

>>> left_strip(right_strip(lst))
['one', None, 'two']
Run Code Online (Sandbox Code Playgroud)

  • 或者`如果item不是None`,以防OP想要保持潜在的零值. (2认同)

小智 5

您可以使用 itertools.dropwhile 来模拟 lstrip:

def lstrip(list):
    return list(itertools.dropwhile(lambda x : x is None, list))

lst = [None, None, 'one', 'two', None]
lstrip(lst)
>> ['one', 'two', None]
Run Code Online (Sandbox Code Playgroud)

rstrip 可以以相同的方式实现,但使用 dropwhile 前后颠倒列表

def rstrip(list):
    return list(reversed(lstrip(reversed(list))))
Run Code Online (Sandbox Code Playgroud)