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].

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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])

Method 2

Here is an example based on your output:

def split_list(test, match):
    idx = [test.index(i) for i in match]
    if sum([i - min(idx) for i in idx]) == sum(range(len(match))
        return [
            test[0:idx[0]],
            test[idx[0]:idx[-1]+1]
        ]

split_list(test=[3, 5, 7, 1, 10, 17], match=[10, 17])

Method 3

Here is a simple working code:

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

def neighbor_splitting():
    for x in test:
        if x == 10:
            index = test.index(x)
            list1 = test[:index]
            list2 = test[index:]
            return list1, list2

# [3, 5, 7, 1]
# [10, 17]


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x