我有来自网站的面包屑,我想从一开始就用lambda表达式删除所有“Home”条目。
类似的东西:
lambda v: v[1:] if v and v[0] == 'Home' else v
但是我想删除倍数,而不仅仅是第一个,并且只从头开始,所以:
['Home', 'Home', 'Home and Garden', 'Home', 'Kitchen']
变为:
['Home and Garden', 'Home', 'Kitchen']
答案 0 :(得分: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需要更多的进口