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

2020-07-04 05:37发布

问题:

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)

回答1:

def reverse_sublist(lst,start,end):
    lst[start:end] = lst[start:end][::-1]
    return lst


回答2:

Partial reverse with no temporary list (replace range with xrange if you use Python 2):

def partial_reverse(list_, from_, to):
    for i in range(0, int((to - from_)/2)):
        (list_[from_+i], list_[to-i]) = (list_[to-i], list_[from_+i])

list_ = [1, 2, 3, 4, 5, 6, 7, 8]
partial_reverse(list_, 3, 7)
print(list_)


回答3:

Easiest way to reverse a list in a partial or complete manner.

listVar = ['a','b','c','d']
def listReverse(list,start,end):
    while(start<end):
        temp = list[start]
        list[start] = list[end] #Swaping
        list[end]=temp
        start+=1
        end-=1
    print(list)


listReverse(listVar,1,3)

Output : - ['a', 'd', 'c', 'b']



回答4:

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



回答5:

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]


回答6:

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"


回答7:

Just use a slice:

>>> lst = [1, 2, 3, 4, 5] 
>>> lst[0:len(lst[3::-1])]=lst[3::-1]
>>> lst
[4, 3, 2, 1, 5]

Or, perhaps easier to understand:

>>> lst = [1, 2, 3, 4, 5] 
>>> sl=lst[3::-1]
>>> lst[0:len(sl)]=sl
>>> lst
[4, 3, 2, 1, 5]


回答8:

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


回答9:

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)


回答10:

I've conducted a tiny experiment and it seems that any assignment to list slice causes memory allocation:

import resource
resource.setrlimit(resource.RLIMIT_AS, (64 * 1024, 64 * 1024))

try:
    # Python 2
    zrange = xrange
    arr_size = 3 * 1024
except NameError:
    # Python 3
    zrange = range
    arr_size = 4 * 1024

arr = list(zrange(arr_size))

# We could allocate additional 100 integers, so there should be enough free memory
# to allocate a couple of variables for indexes in the statement below
#   additional_memory = list(zrange(100))

# MemoryError is raised here
arr[:] = zrange(arr_size)

So you have to use for loop to reverse a sublist in place.

PS: If you want to repeat this test, you should ensure that setrlimit RLIMIT_AS works fine on your platform. Also arr_size may vary for different python implementations.



回答11:

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

Suppose you have to reverse 2nd position to 4th position in place.

lst[2:5] = lst[2:5][::-1]

Output:

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