[英]In a list of strings, find a phrase within the string and append two integers (x..y) in string to a list . Python
[英]Python: Find X to Y in a list of strings
我有大約100個左右元素的列表,實際上是一封電子郵件,每行都是一個元素。 該列表略有變化,因為其中包含\\ n的行被放在單獨的元素中,因此我不能簡單地使用固定值進行切片。 我本質上需要一個可變的開始和結束短語(也需要進行部分搜索,因為我的一個開始短語實際上可能是Total Cost: $13.43
所以我只使用Total Cost:
。)End短語也是如此。 我也不希望在返回列表中包含開始/停止短語。 綜上所述:
>>> email = ['apples','bananas','cats','dogs','elephants','fish','gee']
>>> start = 'ban'
>>> stop = 'ele'
# the magic here
>>> print new_email
['cats', 'dogs']
筆記
解
只是為了玩笑,感謝大家的幫助,這是我的最終代碼:
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]
它返回一個列表,其中包含元素的開始和結束位置,如果找不到相應的值,則默認為0和-1。 (0是第一個元素,-1是最后一個元素)。
解決方案-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']
要滿足元素可能不在列表中的條件:
>>> 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']
基於itertools
的方法:
import itertools
email = ['apples','bananas','cats','dogs','elephants','fish','gee']
start, stop = 'ban', 'ele'
findstart = itertools.dropwhile(lambda item: not item.startswith(start), email)
findstop = itertools.takewhile(lambda item: not item.startswith(stop), findstart)
print list(findstop)[1:]
// ['cats', 'dogs']
干得好:
>>> email = ['apples','bananas','cats','dogs','elephants','fish','gee']
>>> start = 'ban'
>>> stop = 'ele'
>>> out = []
>>> appending = False
>>> for item in email:
... if appending:
... if stop in item:
... out.append(item)
... break
... else:
... out.append(item)
... elif start in item:
... out.append(item)
... appending = True
...
>>> out.pop(0)
'bananas'
>>> out.pop()
'elephants'
>>> print out
['cats', 'dogs']
我認為我的版本比其他答案更具可讀性,不需要任何導入=)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.