1

我有来自网站的面包屑,我想用 lambda 表达式从头开始删除所有“主页”条目。

就像是:

lambda v: v[1:] if v and v[0] == 'Home' else v

但我想删除倍数,而不仅仅是第一个,而且只是从头开始,这样:

['Home', 'Home', 'Home and Garden', 'Home', 'Kitchen']

变成:

['Home and Garden', 'Home', 'Kitchen']
4

1 回答 1

5

也许这就是你想要的lambda

>>> F = lambda v: F(v[1:]) if v and v[0] == 'Home' else v
>>> L = ['Home', 'Home', 'Home and Garden', 'Home', 'Kitchen']
>>> F(L)
['Home and Garden', 'Home', 'Kitchen']

然而,这将是低效的,Python 已经为此提供了工具:

>>> from itertools import dropwhile
>>> L = ['Home', 'Home', 'Home and Garden', 'Home', 'Kitchen']
>>> list(dropwhile(lambda x: x == 'Home', L))
['Home and Garden', 'Home', 'Kitchen']

或者:

>>> from functools import partial
>>> from operator import eq
>>> from itertools import dropwhile
>>> L = ['Home', 'Home', 'Home and Garden', 'Home', 'Kitchen']
>>> list(dropwhile(partial(eq, "Home"), L))
['Home and Garden', 'Home', 'Kitchen']

哪个应该更快,bur 需要更多的导入

于 2013-04-13T01:24:03.823 回答