7

I have a list similar to below

['a','b','c','d','e','f','g','h','i','j']

and I would like to separate by a list of index

[1,4]

In this case, it will be

[['a'],['b','c'],['d','e','f','g','h','i','j']]

As

[:1] =['a']

[1:4] = ['b','c']

[4:] = ['d','e','f','g','h','i','j']

Case 2: if the list of index is

[0,6]

It will be

[[],['a','b','c','d','e'],['f','g','h','i','j']]

As

[:0] = []

[0:6] = ['a','b','c','d','e']

[6:] = ['f','g','h','i','j']

Case 3 if the index is

[2,5,7]

it will be [['a','b'],['c','d','e'],['h','i','j']] As

[:2] =['a','b']
[2:5] = ['c','d','e']
[5:7] = ['f','g']
[7:] = ['h','i','j']
Platalea Minor
  • 877
  • 2
  • 9
  • 22
  • If your question is how to obtain these sublists: why not use a simple loop? – offeltoffel Jan 15 '20 at 09:54
  • This sounds only 99% like a homework. What do you want to achieve with this? Or in other words, what does the homework want you to do? You allready split lists based on a set of indexes. – hajef Jan 15 '20 at 09:55
  • 1
    Does this answer your question? [Split a list into parts based on a set of indexes in Python](https://stackoverflow.com/questions/1198512/split-a-list-into-parts-based-on-a-set-of-indexes-in-python) – Georgy Jan 15 '20 at 10:04
  • 2
    The slices that you are showing aren't consistent. `[0:6] = ['a','b','c','d','e']` should be `['a','b','c','d','e','f']` and `[1:4] = ['b','c']` should be `['b','c','d']` – Alex Jan 15 '20 at 10:05

4 Answers4

8

Something along these lines:

mylist = ['a','b','c','d','e','f','g','h','i','j']
myindex = [1,4]

[mylist[s:e] for s, e in zip([0]+myindex, myindex+[None])]

Output

[['a'], ['b', 'c', 'd'], ['e', 'f', 'g', 'h', 'i', 'j']]
Fourier
  • 2,795
  • 3
  • 25
  • 39
2

This solution is using numpy:

import numpy as np

def do_split(lst, slices):
    return [sl.tolist()for sl in np.split(lst, slices)]

splits = do_split(a, [2,5,7])

Out[49]:
[['a', 'b'], ['c', 'd', 'e'], ['f', 'g'], ['h', 'i', 'j']]

cristian hantig
  • 1,110
  • 1
  • 12
  • 16
1
a = [1,2,3,4,5,6,7,8,9,10]

newlist = []

divide = [2,5,7]
divide = [0]+divide+[len(a)]
for i in range(1,len(divide)):
  newlist.append(a[divide[i-1]:divide[i]])

print(newlist)

Output:

[[1, 2], [3, 4, 5], [6, 7], [8,9,10]]
Strange
  • 1,460
  • 1
  • 7
  • 18
0

I wrote this function to do what you're asking

def splitter(_list, *args):
    args_list = [0]
    args_list += args
    args_list.append(len(_list))
    new_list = []
    for i, arg in enumerate(args_list):
        try:
            new_list.append(_list[arg:args_list[i+1]])

        except IndexError:
            continue
    return new_list

The function can be used like this:

mylist = ['1', '2', '3', '4', '5', '6']
splitter(mylist, 2, 4)

Which returns:

[['1', '2'], ['3', '4'], ['5', '6']]