我编写了这个函数来过滤列表,以便在看到给定项目后显示所有项目。有点类似于内置字符串方法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') == []
答案 0 :(得分:5)
它不是那么紧凑,但是如何:
def ignore_until(the_list, match):
try:
return the_list[the_list.index(match):]
except ValueError:
return []
my_list = ['red','orange','yellow','green']
print ignore_until(my_list, 'yellow') # => ['yellow','green']
print ignore_until(my_list, 'blue') # => []
答案 1 :(得分:3)
为什么不使用python yourlist.index(match)
来查找索引然后应用列表切片。如果未找到匹配项,则yourlist.index
会抛出错误,因此您需要处理该错误。
def ignore_until(yourlist, match):
try:
return yourlist[yourlist.index(match):]
except ValueError:
return []
答案 2 :(得分:2)
这是一个版本,它可以重现str.partition的功能(即返回三个列表):
def partition(lst, item):
if item in lst:
n = lst.index(item)
return lst[:n], [item], lst[n+1:]
else:
return lst, [], []
print partition(range(10), 7)
这是一个适用于任意迭代的版本,而不是必需的列表:
def partition(it, item):
a = [[]]
for x in it:
if x == item and len(a) == 1:
a.append([item])
a.append([])
else:
a[-1].append(x)
return a
print partition((x for x in range(10)), 7)
改进版本:
def partition(it, item):
a = []
for x in it:
if x == item:
return a, [item], list(it)
a.append(x)
return a, [], []
print partition((x for x in range(10)), 7)
print partition((x for x in range(10)), 17)
答案 3 :(得分:1)
def ignore_until(the_list, match):
try:
return my_list[the_list.index(match):]
except ValueError:
return []
答案 4 :(得分:1)
试试这个:
def ignore_until(the_list, match):
try:
return [the_list[the_list.index(object):] for object in l if object == match][0]
except IndexError:
return []
有点难读,但它很紧凑。
答案 5 :(得分:1)
您是否考虑过使用list.index()方法?它返回指定项的第一个实例的索引(否则会引发错误)
def ignore_until(the_list, match):
if match in the_list:
index = the_list.index(match)
return the_list[index:]
else:
return []