ira ira - 6 months ago 10
Python Question

Elegant way to split list on particular values

I am trying to think of an elegant way to do the following task:

I have a list of mixed types, and would like to 'break' the list on one of the types. For example, I might have

['a', 1, 2, 3, 'b', 4, 5, 6]


and I'd like to return something like

{'a': [1, 2, 3],
'b': [4, 5, 6]}


The motivation for doing this is the following: I have some html data that is split up as follows

<div ...> ... </div>
<table> ... </table>
<table> ... </table>

<div ...> ... </div>
<table> ... </table>
<table> ... </table>
...
<table> ... </table>


Which I would like to organize into blocks delimited by the divs. If anyone can think of a nicer approach than what I proposed above that would be great too! Thanks.

Answer

Code -

from collections import defaultdict

arr = ['a', 1, 2, 3, 'b', 4, 5, 6]

d = defaultdict(list)

cur_key = arr[0]

for value in arr[1:]:
    if type(value) != type(cur_key):
        d[cur_key].append(value)
    else:
        cur_key = value

print(d)

Output -

defaultdict(<class 'list'>, {'b': [4, 5, 6], 'a': [1, 2, 3]})