考慮:
li=['Week 9 (28/09/15) MA4/PGDE/ BMus','0900-1000 MA4/PGDE Lecture ALT ', '1100-1200 PS Tutorials Groups 1-9 ONLY ','1300-1400 PS Lecture ALT', '1500-1600 PS Lecture ALT ', 'Week 10... ', 'more on 10', 'and more', 'Week 11... ', 'more on 11', 'and more',]
您可以使用groupby
像這樣:
from itertools import groupby
result=[]
temp=[]
for k, g in groupby(li, key=lambda s: s.lower().startswith('week')):
if k:
if temp:
result.append(temp)
temp=list(g)
else:
temp.extend(list(g))
else:
result.append(temp)
>>> results
[['Week 9 (28/09/15) MA4/PGDE/ BMus', '0900-1000 MA4/PGDE Lecture ALT ', '1100-1200 PS Tutorials Groups 1-9 ONLY ', '1300-1400 PS Lecture ALT', '1500-1600 PS Lecture ALT '], ['Week 10... ', 'more on 10', 'and more'], ['Week 11... ', 'more on 11', 'and more']]
你也可以做切片和zip(同一列表),像這樣:
>>> idxs=[i for i, e in enumerate(li) if s.lower().startswith('week')]+[len(li)]
>>> [li[x:y] for x, y in zip(idxs, idxs[1:])]
[['Week 9 (28/09/15) MA4/PGDE/ BMus', '0900-1000 MA4/PGDE Lecture ALT ', '1100-1200 PS Tutorials Groups 1-9 ONLY ', '1300-1400 PS Lecture ALT', '1500-1600 PS Lecture ALT '], ['Week 10... ', 'more on 10', 'and more'], ['Week 11... ', 'more on 11', 'and more']]
請包括一個最小的,完整的,可驗證的例子,以及到目前爲止所嘗試的。 –
堆棧溢出不是代碼寫入服務!請顯示你已經嘗試了哪些代碼,哪些不起作用。請參閱[this](http://stackoverflow.com/help/mcve)瞭解如何創建最小,完整,可驗證的示例。 – MarkyPython