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

2020-07-04 05:54发布

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 what it's supposed to do:

>>> lst = [1, 2, 3, 4, 5] 
>>> reverse_sublist (lst,0,4) 
>>> lst  [4, 3, 2, 1, 5]

I created a function and it works, but I'm not sure is it's in place. This is my code:

def reverse_sublist(lst,start,end):
    sublist=lst[start:end]
    sublist.reverse()
    lst[start:end]=sublist
    print(lst)

11条回答
smile是对你的礼貌
2楼-- · 2020-07-04 06:16

lst[::-1] is the idiomatic way to reverse a list in Python, The following show how and that it was in-place:

>>> lst = [1, 2, 3, 4, 5]
>>> id(lst)
12229328
>>> lst[:] = lst[::-1]
>>> lst
[5, 4, 3, 2, 1]
>>> id(lst)
12229328
查看更多
该账号已被封号
3楼-- · 2020-07-04 06:19
def reverse_sublist(lst,start,end):
    lst[start:end] = lst[start:end][::-1]
    return lst
查看更多
够拽才男人
4楼-- · 2020-07-04 06:23

I have two ways for in-place reversal, the simple way is to loop through the list half-way, swapping the elements with the respective mirror-elements. By mirror-element I mean (first, last), (2nd, 2nd-last), (3rd, 3rd-last), etc.

def reverse_list(A):
    for i in range(len(A) // 2): # half-way
        A[i], A[len(A) - i - 1] = A[len(A) - i - 1], A[i] #swap
    return A

The other way is similar to the above but using recursion as opposed to a "loop":

def reverse_list(A):
    def rev(A, start, stop):
        A[start], A[stop] = A[stop], A[start] # swap
        if stop - start > 1: # until halfway
            rev(A, start + 1, stop - 1)
        return A

    return rev(A, 0, len(A) - 1)
查看更多
该账号已被封号
5楼-- · 2020-07-04 06:26

... I'm not sure is it's in place.

...

lst[start:end]=sublist

Yes, it's in place. lst is never rebound, only its object mutated.

查看更多
虎瘦雄心在
6楼-- · 2020-07-04 06:26

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]
查看更多
祖国的老花朵
7楼-- · 2020-07-04 06:26

Not sure if you have a similar problem as mine, but i needed to reverse a list in place.

The only piece I was missing was [:]

exStr = "String"

def change(var):
  var[:] = var[::-1] # This line here

print(exStr) #"String"
change(exStr)
print(exStr) #"gnirtS"
查看更多
登录 后发表回答