Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Splitting list in Python if two elements are next to each other

how can i split a list based on neighboring elements, so if i have a list such as

test = [3,5,7,1,10,17]

and i want to split the list if element 10 and 17 are next to each other so that the split happens between [3,5,7,1] and [10,17].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know there is groupby but i could only figure out how to use that to check if one element is present and then split, but not two after each other.

pseudocode:

for i in list:
      if element[i] == 10 and element[i+1] == 17:
                  splitlist() # split before elements 10

>Solution :

You can zip() the list with an offset of itself to get pairs. Then find the index of the pair you are looking for (assuming this happens once or you only care about the first). Then splice the list:

test = [3,5,7,1,10,17]

def partition_on_pair(test, pair):
    index = next((i for i, n in enumerate(zip(test, test[1:])) if n == pair), len(test))
    return test[:index], test[index:]

partition_on_pair(test, (10, 17))
# ([3, 5, 7, 1], [10, 17])

partition_on_pair(test, (10, 19)) # doesn't exist, so you get an empty
#([3, 5, 7, 1, 10, 17], [])


partition_on_pair(test, (5, 7))
#([3], [5, 7, 1, 10, 17])

partition_on_pair(test, (3,5))
#([], [3, 5, 7, 1, 10, 17])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading