Yi Zhao
Yi Zhao

Reputation: 336

How to split python list into segments based on elements' attributes?

I have a list like:

[
    {'p': 0},
    {'p': 1},   
    {'p': 1},
    {'p': 0},
    {'p': 0},
    {'p': 2}            
]

I want to split it into segments based on attribute p, so the result would be:

[[{'p':0}], [{'p':1}, {'p':1}], [{'p':0}, {'p':0}], [{'p':2}]]

Upvotes: 0

Views: 66

Answers (1)

David Meu
David Meu

Reputation: 1545

As mentioned you can use itertools:

import itertools

list_p = [
    {'p': 0},
    {'p': 1},
    {'p': 1},
    {'p': 0},
    {'p': 0},
    {'p': 2}
]

list_p_groups = []

for key, group in itertools.groupby(list_p):
    list_p_groups.append(list(group))
for item in list_p_groups:
    print(item)

Outputs:

[{'p': 0}]
[{'p': 1}, {'p': 1}]
[{'p': 0}, {'p': 0}]
[{'p': 2}]

Upvotes: 2

Related Questions