Python: Split a list into sub-lists based on index ranges

后端 未结 5 2093
感情败类
感情败类 2020-12-10 10:43

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]
5条回答
  •  误落风尘
    2020-12-10 11:30

    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...

提交回复
热议问题