根据列表项内容拆分列表(字符串)

时间:2016-03-14 21:51:13

标签: python nested-lists

我有一个包含大学讲座时间和科目的列表。

['第9周(2015年9月28日)MA4 / PGDE / BMus','0900-1000 MA4 / PGDE讲座ALT','1100-1200 PS教程组1-9 ONLY','1300-1400 PS讲座ALT','1500-1600 PS讲座ALT','第10周......等等......

共有44周,如何使用'Week'字符串作为触发器将列表拆分为子列表,为每周的讲座提供子列表?如下

[['第9周(28/09/15)MA4 / PGDE / BMus','0900-1000 MA4 / PGDE讲座ALT','1100-1200 PS教程组1-9 ONLY','1300-1400 PS讲座ALT','1500-1600 PS讲座ALT',['第10周......等等......

我没有任何代码...这就是为什么我在问我是否以及如何做到这一点!

2 个答案:

答案 0 :(得分: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']]

您也可以像这样进行切片和压缩(在同一个列表中):

>>> 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']]

答案 1 :(得分: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是你的起始数组,排列的是数组,由数组组成,从元素周开始。