How do I reverse a sublist in a list in place?

前端 未结 12 2589
-上瘾入骨i
-上瘾入骨i 2021-02-20 01:24

I\'m supposed to create a function, which input is a list and two numbers, the function reverses the sublist which its place is indicated by the two numbers. for example this is

12条回答
  •  执笔经年
    2021-02-20 02:07

    Try some crazy slicing, see Explain Python's slice notation and http://docs.python.org/2.3/whatsnew/section-slices.html

    x = [1,2,3,4,5,6,7,8]
    
    def sublist_reverse(start_rev, end_rev, lst):
        return lst[:end_rev-1:start_rev-1]+lst[:[end_rev]
    
    print sublist_reverse(0,4,x)
    

    [out]:

    [8, 7, 6, 5, 4, 3, 2, 1]
    

提交回复
热议问题