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

后端 未结 5 2088
感情败类
感情败类 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:43

    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.

提交回复
热议问题