Reputation: 336
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
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