split python list given the index start
<p>I have looked at this:<a href="http://stackoverflow.com/questions/18570740/python-split-a-list-into-sub-lists-based-on-index-ranges">Split list into sublist based on index ranges</a></p>

<p>But my problem is slightly different.
I have a list</p>

<pre><code>List = ['2016-01-01', 'stuff happened', 'details', 
        '2016-01-02', 'more stuff happened', 'details', 'report']
</code></pre>

<p>I need to split it up into sublists based on the dates. Basically it's an event log but due to shitty DB design the system concats separate update messages for an event into one big list of strings.
I have:</p>

<pre><code>Event_indices = [i for i, word in enumerate(List) if 
                 re.match(date_regex_return_all = "(\d+\-\d+\-\d+",word)]
</code></pre>

<p>which for my example will give:</p>

<pre><code>[0,3]
</code></pre>

<p>Now I need split the list into separate lists based on the indexes. So for my example ideally I want to get:</p>

<pre><code>[List[0], [List[1], List[2]]], [List[3], [List[4],  List[5], List[6]] ]
</code></pre>

<p>so the format is:</p>

<pre><code>[event_date, [list of other text]], [event_date, [list of other text]]
</code></pre>

<p>There are also edge cases where there is no date string which would be the format of:</p>

<pre><code>Special_case = ['blah', 'blah', 'stuff']
Special_case_2 = ['blah', 'blah', '2015-01-01', 'blah', 'blah']

result_special_case = ['', [Special_case[0], Special_case[1],Special_case[2] ]]
result_special_case_2 = [ ['', [ Special_case_2[0], Special_case_2[1] ] ], 
                          [Special_case_2[2], [ Special_case_2[3],Special_case_2[4] ] ] ]
</code></pre>

<p>Try:</p>

<pre><code>def split_by_date(arr, patt='\d+\-\d+\-\d+'):
    results = []
    srch = re.compile(patt)
    rec = ['', []]
    for item in arr:
        if srch.match(item):
            if rec[0] or rec[1]:
                results.append(rec)
            rec = [item, []]
        else:
            rec[1].append(item)
    if rec[0] or rec[1]:
        results.append(rec)
    return results
</code></pre>

<p>Then:</p>

<pre><code>normal_case = ['2016-01-01', 'stuff happened', 'details', 
               '2016-01-02', 'more stuff happened', 'details', 'report']
special_case_1 = ['blah', 'blah', 'stuff', '2016-11-11']
special_case_2 = ['blah', 'blah', '2015/01/01', 'blah', 'blah']

print(split_by_date(normal_case))
print(split_by_date(special_case_1))
print(split_by_date(special_case_2, '\d+\/\d+\/\d+'))
</code></pre>

python string list