2011-05-09 43 views
1

我有它包含以下字符串列表小名單:的Python:如何分割一列到未知數量的基礎上分隔符

MainList
'00:00'
「 00:01'
'00:02'
'00:03'
'00:04'
'00:00'
'00:01'
'00:02'
'00:03'
'00:04'

我想這個分成每當'00列表的數量較少:00' 遇到因爲'00:00' 是贏了」的唯一因素噸變化:

希望的輸出:
的List1
'00:00'
'00:01'
'00:02'
'00:03'
'00:04'

列表2
'00:00'
'00:01'
'00:02'
'00:03'
'00:04'

我試圖尋找列表切片,但問題是最後的值,因此,元素的數量可能會改變。此外,我不知道有多少小名單,我需要

回答

5

我通常這樣做:

def splitby(lst, breaker='00:00'): 
    current = [] 
    it = iter(lst) 
    first = next(it) 
    assert first==breaker, "`lst` must begin with `breaker`" 
    for item in it: 
     if item == breaker: 
      yield current 
      current = [] 
     current.append(item) 
    yield current 

必然itertools解決方案是一個比較普遍:

from itertools import groupby 

class splitter(object): 

    def __init__(self, breaker): 
     self.breaker = breaker 
     self.current_group = 0 

    def __call__(self, item): 
     if item == self.breaker: 
      self.current_group+=1 
     return self.current_group 

    def group(self, items): 
     return (list(v) for k,v in groupby(items,self)) 

print list(splitter('00:00').group(items)) 
+0

+1爲發電機愛 – 2011-05-09 12:58:04

+0

嗨,我已經走了你的第一個解決方案 - 返回一個發電機。 :)但是,我似乎無法將生成器拆分爲顯式列表?我運行 'code: for splitby(lst): print(x) ' '但是我怎樣才能將每個列表對象分配給它自己的唯一名稱,例如,結束時使用'list1'和'list2'生成器對象,而不是隻有x? 感謝您的迴應,發電機是我以前從未遇到過的東西! – cbros2008 2011-05-09 16:13:33

+0

@ cbros2008:只要做'splitted = list(splitby(lst))'然後你可以使用'splitted [0]'等 – 2011-05-09 17:08:28

3

在一個明確的方式,你可以做這樣的(我怎麼會動態地創建更小名單的n個):

sep = '00:00' 
split_list = [] 
for item in Mainlist: 
    if item == sep: 
     split_list.append([item]) 
    else: 
     split_list[-1].append(item) 

print split_list 
+0

我喜歡這個,因爲它使相當明顯發生了什麼。 – kqr 2013-09-16 09:38:35

2

Comprehens離子是你最好的朋友:)。只是兩行:

>>> a=['00:00', '00:01', '00:02', '00:03', '00:00', '00:01', '00:02'] 
>>> found=[index for index,item in enumerate(a) if item=='00:00'] + [len(a)] 
>>> [a[found[i]:found[i+1]] for i in range(len(found)-1)] 
[['00:00', '00:01', '00:02', '00:03'], ['00:00', '00:01', '00:02']] 

這裏是我們做什麼:

我們尋找分隔符的位置,並獲得其中包含的分隔符索引列表:

>>> found=[index for index,item in enumerate(a) if item=='00:00'] 
>>> found 
[0, 4] 

我們將LEN(一)包括最後一個字典。

和創建以極快的一個新的列表與創建索引:

>>> [a[found[i]:found[i+1]] for i in range(len(found)-1)] 
[['00:00', '00:01', '00:02', '00:03'], ['00:00', '00:01', '00:02']] 
+0

謝謝你的回覆。我喜歡抓取分隔符索引的想法。 – cbros2008 2011-05-10 08:58:03

0

我能想到的另一種方式:-)

def list_split(a): 
    #a=['00:00', '00:01', '00:02', '00:03', '00:00', '00:01', '00:02'] 
    output = [] 
    count = 0 

    if len(a) < 1: 
     output.append(a) 
     return output 

    for i, item in enumerate(a[1:]): 
     if item == a[0]: 
      output.append(a[count:i+1]) 
      count = i + 1 
    else: 
     output.append(a[count:]) 
     return output 
相關問題