我编写了这个函数来过滤列表以在看到给定项目后显示所有项目。有点类似于内置的字符串方法str.rpartition(sep)
。我觉得有一种更紧凑的方法可以做到这一点,也许使用列表理解。有任何想法吗?
def ignore_until(the_list, match):
# Ignore all items in the_list prior to match
found = False
for index, item in enumerate(the_list):
if item == match:
found = True
break
if found:
return the_list[index:]
else:
return []
my_list = ['red','orange','yellow','green']
assert ignore_until(my_list, 'yellow') == ['yellow','green']
assert ignore_until(my_list, 'blue') == []
编辑:
在看到上述问题的答案后,我意识到 6 个答案中有 5 个侧重于index()
列表数据类型的内置方法。实际上,我需要使用正则表达式,并且没有意识到从我的问题中省略它会影响人们的答案。这是正则表达式代码:
import re
def ignore_until(the_list, pattern):
# Ignore all items in the_list prior to the item containing pattern.
found = False
for index, item in enumerate(the_list):
if re.search(string=item, pattern=pattern):
found = True
break
if found:
return the_list[index:]
else:
return []
my_list = ['red','orange','yellow','green']
assert ignore_until(my_list, 'yellow') == ['yellow','green']
assert ignore_until(my_list, 'blue') == []