I’m looking for a way how to split a list into lists ad given index. Sometimes can be a few lists when a few indexes are given.
For example, there is a list:
0 item1
1 item2
2 item3
3 item4
…
indexes are:
1
3
Would like to achieve lists:
0:
0 item1
1:
0 item2
1 item3
2:
0 item4
1 item5
…
Hi, you duplicate the index list
for one you insert 0 at the head
for the other at the end of the list the count of the list you make the difference that you send in list chop
edit:
# Function: Split list before indices
def splitList(lst, inds):
# Initial variables
counter = 1
outLists, curList = [],[]
# For each item...
for i in lst:
# Append to current list
curList.append(i)
# If we split at the next index...
if counter in inds:
# Append current list and reset it
outLists.append(curList)
curList = []
# Uptick counter
counter += 1
# If we have a current list, append it
if len(curList) > 0:
outLists.append(curList)
# Return the outcome
return outLists
# Test data
test_list = [0,1,2,3,4,5,6,7,8,9]
ind_split = [1,3,5]
# Test print
print(splitList(test_list, ind_split))
A cleaner but more complex Python approach would be a function using the yield statement, but above should work fine also.
# Function: Split list before indices
def splitList(lst, inds):
# Initial variables
counter = 1
curList = []
# For each item...
for i in lst:
# Append to current list
curList.append(i)
# If we split at the next index...
if counter in inds:
# Yield current list
yield curList
curList = []
# Uptick counter
counter += 1
# If we have a current list, yield it
if len(curList) > 0:
yield curList
# Test data
test_list = [0,1,2,3,4,5,6,7,8,9]
ind_split = [1,3,5]
# Test print
outcome = list(splitList(test_list, ind_split))
print(outcome)