2016-03-14 144 views
-3

我有一個包含大學講座時間和主題的列表。根據列表項目內容(字符串)拆分列表

['第9周(28/09/15)MA4/PGDE/BMus','0900-1000 MA4/PGDE Lecture ALT','1100-1200 PS Tutorials Groups 1-9 ONLY','1300-1400 PS講座ALT「,」1500-1600 PS講座ALT「,」第10周...等等......

總共有44個星期,我怎樣才能使用'周「字符串作爲觸發器,給我每個星期講座的子列表?如下所示

[['第9周(28/09/15)MA4/PGDE/BMus','0900-1000 MA4/PGDE Lecture ALT','1100-1200 PS Tutorials Groups 1-9 ONLY',' 1300-1400 PS講座ALT','1500-1600 PS講座ALT'],['第10周...等等...

我沒有任何代碼......這就是爲什麼我是問我是否以及如何做到這一點!

+0

請包括一個最小的,完整的,可驗證的例子,以及到目前爲止所嘗試的。 –

+0

堆棧溢出不是代碼寫入服務!請顯示你已經嘗試了哪些代碼,哪些不起作用。請參閱[this](http://stackoverflow.com/help/mcve)瞭解如何創建最小,完整,可驗證的示例。 – MarkyPython

回答

0

考慮:

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']] 
0
allWeeks = [] 
arranged = [] 

current = [] 
for i in range(len(allWeeks)): 

    if ("Week" in allWeeks[i]): 
     arranged.append(current) 
     current = [] 
     current.append(allWeeks[i]) 
    elif (i == len(allWeeks) - 1): 
     current.append(allWeeks[i]) 
     arranged.append(current) 
    else: 
     current.append(allWeeks[i]) 

for i in arranged: 
    print (i) 

allWeeks是你的起點數組和排列是由數組組成的數組,從元素Week開始。