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

前端 未结 12 2673
-上瘾入骨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:17

    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
    
    0 讨论(0)
  • 2021-02-20 02:17

    Two methods in-place and constant memory:

    def reverse_swap(arr, start=None, end=None):
        """
        Swap two edge pointers until meeting in the center.
        """
    
        if start is None:
            start = 0
        if end is None:
            end = len(arr)
    
        i = start
        j = end - 1
        while i < j:
            arr[i], arr[j] = arr[j], arr[i]
            i += 1
            j -= 1
    
    def reverse_slice(arr, start=None, end=None):
        """
        Use python slice assignment but use a generator on the right-hand-side
        instead of slice notation to prevent allocating another list.
        """
    
        if start is None:
            start = 0
        if end is None:
            end = len(arr)
    
        arr[start:end] = (arr[i] for i in range(end - 1, start - 1, -1))
    
    0 讨论(0)
  • 2021-02-20 02:23
    def reverse_sublist(lst,start,end):
        lst[start:end] = lst[start:end][::-1]
        return lst
    
    0 讨论(0)
  • 2021-02-20 02:23

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

    0 讨论(0)
  • 2021-02-20 02:26

    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_)
    
    0 讨论(0)
  • 2021-02-20 02:27

    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"
    
    0 讨论(0)
提交回复
热议问题