UPDATED:
In python, how do i split a list into sub-lists based on index ranges
e.g. original list:
list1 = [x,y,z,a,b,c,d,e,f,g]
using index ranges 0 - 4:
list1a = [x,y,z,a,b]
using index ranges 5-9:
list1b = [c,d,e,f,g]
thanks!
I already known the (variable) indices of list elements which contain certain string and want to split the list based on these index values.
Also need to split into variable number of sub-lists! i.e:
list1a
list1b
.
.
list1[x]
list1a=list[:5]
list1b=list[5:]
In python, it's called slicing. Here is an example of python's slice notation:
>>> list1 = ['a','b','c','d','e','f','g','h', 'i', 'j', 'k', 'l']
>>> print list1[:5]
['a', 'b', 'c', 'd', 'e']
>>> print list1[-7:]
['f', 'g', 'h', 'i', 'j', 'k', 'l']
Note how you can slice either positively or negatively. When you use a negative number, it means we slice from right to left.
If you already know the indices:
list1 = ['x','y','z','a','b','c','d','e','f','g']
indices = [(0, 4), (5, 9)]
print [list1[s:e+1] for s,e in indices]
Note that we're adding +1 to the end to make the range inclusive...
list1=['x','y','z','a','b','c','d','e','f','g']
find=raw_input("Enter string to be found")
l=list1.index(find)
list1a=[:l]
list1b=[l:]
Source: Stackoverflow.com