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

后端 未结 5 2078
感情败类
感情败类 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:18
    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:]
    
    0 讨论(0)
  • 2020-12-10 11:23

    Note that you can use a variable in a slice:

    l = ['a',' b',' c',' d',' e']
    c_index = l.index("c")
    l2 = l[:c_index]
    

    This would put the first two entries of l in l2

    0 讨论(0)
  • 2020-12-10 11:28
    list1a=list[:5]
    list1b=list[5:]
    
    0 讨论(0)
  • 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...

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题