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

Time:04-30

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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]

  • Related