# Slicing a list at integer of when an element is different from the previous

0

I need to be able to slice a list of points into multiple sublists, to act as a guide for slicing another list.

My list right now is y_vals = [a,a,a,a,a,a,b,b,b,b,b,b,b,b,b,b,b,c,c,c,c,c…] and I need it to slice every time the number changes. a, b and c are actual numbers, but the numbers are rather long, so I typed it out in a,b,c.

I wanted to use the slicing method of [:x], but it’s a list of 5000 over numbers, and I’m not sure how to slice a list. Thank you in advance!

split data at change.gh (10.6 KB)

Looks a little clunky to me. It could probably be scripted in a couple of lines.

Couple ways to go…here is one using Create Set, Member Index, and Partition List.

good point, my solution would duplicate values if they repeated…You could go a scripting/python route. Full Disclosure: I googled and grabbed this example from stackoverflow!

``````from collections import Counter
import ghpythonlib.treehelpers as th

C = Counter(x)
a = th.list_to_tree([[k,]*v for k,v in C.items()])
``````

(set typehint for ghpython component to list access)

EDIT: For closure, if you are starting with a sorted list, this would also work:

1 Like

Oh, they wouldn’t because I sorted them, actually, so that’s why they end up as a whole string of a, then b, then c, but I couldn’t figure how to split this list to use it as a tree data after I flattened it earlier, and I couldn’t unflatten the earlier step haha.

This worked really well to achieve what I wanted thank you!

1 Like

Hello,

You could probably use a Counter from the collections module to do this. If you pass your list to it then iterate over the keys and values, the value will be the number of items

1 Like