Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list into parts based on a set of indexes in Python

Tags:

python

list

What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below

indexes = [5, 12, 17] list = range(20) 

return something like this

part1 = list[:5] part2 = list[5:12] part3 = list[12:17] part4 = list[17:] 

If there are no indexes it should return the entire list.

like image 874
drjeep Avatar asked Jul 29 '09 07:07

drjeep


People also ask

How do you split a specific index in Python?

Use the str. split() method to split the string into a list. Access the list element at the specific index. Assign the result to a variable.

How do you split a list into delimiter in Python?

Use split() method to split by delimiter. If the argument is omitted, it will be split by whitespace, such as spaces, newlines \n , and tabs \t . Consecutive whitespace is processed together. A list of the words is returned.

How do you separate items in a list?

Usually, we use a comma to separate three items or more in a list. However, if one or more of these items contain commas, then you should use a semicolon, instead of a comma, to separate the items and avoid potential confusion.


1 Answers

This is the simplest and most pythonic solution I can think of:

def partition(alist, indices):     return [alist[i:j] for i, j in zip([0]+indices, indices+[None])] 

if the inputs are very large, then the iterators solution should be more convenient:

from itertools import izip, chain def partition(alist, indices):     pairs = izip(chain([0], indices), chain(indices, [None]))     return (alist[i:j] for i, j in pairs) 

and of course, the very, very lazy guy solution (if you don't mind to get arrays instead of lists, but anyway you can always revert them to lists):

import numpy partition = numpy.split 
like image 113
fortran Avatar answered Sep 23 '22 19:09

fortran