Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a list into sublists that begin with the delimiting character? [closed]

Tags:

python

list

split

  • I would like to split a list into sublists that begin with the delimiting character
    • The delimiting character must be kept
    • The delimiting character must be the first character of each sublist

Example:

delimiter = "x" 
input = ["x","a","x","x",1,2,3,"a","a","x","e"]
output = [["x","a"], ["x"], ["x",1,2,3,"a","a"], ["x","e"]]
  • In addition to the solutions below, see Python splitting a list based on a delimiter word
    • The question is similar, but the expected output is slightly different. For instance, the top solution there, returns and empty list at index 0.
like image 205
Rosty Koryaha Avatar asked Jul 02 '20 09:07

Rosty Koryaha


2 Answers

Step 1: Find the indices where the variable occurs in your list:

idx = [ix for ix, val in enumerate(input) if val==variable]

Step 2: Generate sub-lists using list slicing:

res = [input[i:j] for i,j in zip(idx, idx[1:]+[len(input)])]

Output

print(res)
# [['x', 'a'], ['x'], ['x', 1, 2, 3, 'a', 'a'], ['x', 'e']]
like image 139
AnsFourtyTwo Avatar answered Nov 01 '22 13:11

AnsFourtyTwo


You can use the below function to get desired output.

Try this :

def splitList(inputList, delim):
    finalList = []
    chunk = []
    for val in inputList:
        if val == delim:
            finalList.append(chunk)
            chunk = [delim]
        else:
            chunk.append(val)
    finalList.append(chunk)        
    return finalList[1:]


my_input_list = ["x","a","x","x",1,2,3,"a","a","x","e"]
my_output = splitList(my_input_list, "x")    #just call the function with input_list and delimiter to split onto.


print(my_output)

>>> [["x","a"],["x"],["x",1,2,3,"a","a"],["x","e"]]
like image 44
Prashant Kumar Avatar answered Nov 01 '22 15:11

Prashant Kumar