简体   繁体   中英

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.

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]})

A solution without imports:

$ cat /tmp/tmp.py
_dict = ['a', 1, 2, 3, 'b', 4, 5, 6]
type_key = str
out = dict()
cur_key = ""

for i in _dict:
    if type(i) == type_key:
        out[i] = list()
        cur_key = i
    else:
        out[cur_key].append(i)

print(out)


$ python /tmp/tmp.py
{'a': [1, 2, 3], 'b': [4, 5, 6]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM