Reputation: 93
I am making a C4D plugin and was wondering: How do you use groupby to split an array based on a contained value?
I send this code over to a splinebuilder function, but if I send the splinelist as is, I get a connection between lines, which don't want.
So I need to send separated lists so the splinebuilder creates sets of those lines, avoiding the interconnection.
#initial contains XYZ vectors
splinelist = [(-200, 0, -200), (0, 0, -200), (200, 0, -200), (-200, 0, 0), (0, 0, 0), (200, 0, 0), (-200, 0, 200), (0, 0, 200), (200, 0, 200)]
#desired handcoded for example separated based on Z value
la = [(-200, 0, -200), (0, 0, -200), (200, 0, -200)]
lb = [(-200, 0, 0), (0, 0, 0), (200, 0, 0)]
lc = [(-200, 0, 200), (0, 0, 200), (200, 0, 200)]
#desired list of lists based on Z value
desiredlist = [[(-200, 0, -200), (0, 0, -200), (200, 0, -200)],[(-200, 0, 0), (0, 0, 0), (200, 0, 0)],[(-200, 0, 200), (0, 0, 200), (200, 0, 200)]]
Upvotes: 0
Views: 127
Reputation: 1431
I think this does what you need:
import itertools
splinelist = [(-200, 0, -200), (0, 0, -200), (200, 0, -200), (-200, 0, 0), (0, 0, 0), (200, 0, 0), (-200, 0, 200), (0, 0, 200), (200, 0, 200)]
grouped = itertools.groupby(splinelist, lambda x : x[2])
desiredlist = [list(group) for key, group in grouped]
print(desiredlist)
Output:
[[(-200, 0, -200), (0, 0, -200), (200, 0, -200)], [(-200, 0, 0), (0, 0, 0), (200, 0, 0)], [(-200, 0, 200), (0, 0, 200), (200, 0, 200)]]
Upvotes: 1