我有一个可能包含100个元素的列表,实际上是一个电子邮件,每行都是一个元素.该列表略有变化,因为其中包含\n的行被放在一个单独的元素中,所以我不能简单地使用固定值进行切片.我基本上需要一个变量的开始和停止短语(也需要部分搜索,因为我的一个开始短语可能实际上是Total Cost: $13.43我将使用的Total Cost:.)与结束短语相同.我也不希望在返回的列表中包含开始/停止短语.综上所述:
>>> email = ['apples','bananas','cats','dogs','elephants','fish','gee']
>>> start = 'ban'
>>> stop = 'ele'
# the magic here
>>> print new_email
['cats', 'dogs']
Run Code Online (Sandbox Code Playgroud)
笔记
解
只是为了好玩,感谢大家的帮助,这是我的最终代码:
def get_elements_positions(stringList=list(), startPhrase=None, stopPhrase=None):
elementPositionStart, elementPositionStop = 0, -1
if startPhrase:
elementPositionStart = next((i for i, j in enumerate(stringList) if j.startswith(startPhrase)), 0)
if stopPhrase:
elementPositionStop = next((i for i, j in enumerate(stringList) if j.startswith(stopPhrase)), -1)
if elementPositionStart + 1 == elementPositionStop - 1:
return elementPositionStart + 1
else:
return [elementPositionStart, elementPositionStop]
Run Code Online (Sandbox Code Playgroud)
它返回一个包含起始和结束元素位置的列表,如果找不到相应的值,则默认为0和-1.(0是第一个元素,-1是最后一个元素).
SOLUTION-B
我做了一个小改动,现在如果列表描述了一个开始和停止位置,导致它之间只有1个元素,它返回那个元素位置作为整数而不是你仍然得到多行返回的列表.
再次感谢!
>>> email = ['apples','bananas','cats','dogs','elephants','fish','gee']
>>> start, stop = 'ban', 'ele'
>>> ind_s = next(i for i, j in enumerate(email) if j.startswith(start))
>>> ind_e = next(i for i, j in enumerate(email) if j.startswith(stop) and i > ind_s)
>>> email[ind_s+1:ind_e]
['cats', 'dogs']
Run Code Online (Sandbox Code Playgroud)
要满足元素可能不在列表中的条件:
>>> def get_ind(prefix, prev=-1):
it = (i for i, j in enumerate(email) if i > prev and j.startswith(prefix))
return next(it, None)
>>> start = get_ind('ban')
>>> start = -1 if start is None else start
>>> stop = get_ind('ele', start)
>>> email[start+1:stop]
['cats', 'dogs']
Run Code Online (Sandbox Code Playgroud)