2016-03-14 128 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开始。